Programatically Add Products to your WooCommerce Cart

I’ve been rebuilding my WooCommerce plugin demos to make them easier to use and understand. For my WooCommerce Delivery Slots demo, I decided to direct people straight to the checkout page. As such, I found myself needing to programatically add a few items to the cart when the page is loaded.

I decided to hook into the wp action, as I could then check which page was being loaded. I then used some WooCommerce methods to add some items to the cart:

Firstly, I check to see if it’s the checkout page. If it is, I then check to see if the cart is empty. Finally, if the cart was empty I add 2 products to the cart programatically.

The method we want to focus on here is WC()->cart->add_to_cart();.

The function accepts 5 parameters:

The first parameter is the $product_id. For simple products, assuming we only want to add 1, we could just enter the product ID and be done with it.

The second parameter is $quantity. Enter any number greater than 0 to add that many of the item to your cart.

As we move on, we can see that it is possible to add variations to the cart using this method. However, you can’t simply enter a $variation_id and hope for the best. You need to enter a $product_id, $quantity, $variation_id, and finally $variation. Let’s look at this in more detail.

Adding a Product Variation to your WooCommerce Cart Programatically

As I just mentioned, you need at to enter at least 4 parameters in order to add a variation to the cart programatically.

Let’s take a look at those parameters:

  • $product_id This is the variable product ID. The parent of our variation.
  • $quantity As explained before, this is the quantity of this product which you want to add to the cart.
  • $variation_id This is the ID of our specific variation. The child of our parent product.
  • $variation This is an array of the select attributes. This is used for displaying the variation data in cart and on the order.

Summary

As you can see, it’s reasonably straightforward to add products to your WooCommerce cart using the helper method available in core. Give it a go! As always, if you get stuck, drop me a comment below.

Leave a Reply

2 Comments on "Programatically Add Products to your WooCommerce Cart"

avatar
  Subscribe  
newest oldest most voted
Notify of
Collins Agbonghama
Guest

I am working on a client project and was having difficulties adding variation to cart. The last parameter to add_to_cart() method did the trick.

Thanks for sharing.

Stephane Martin
Guest

Thanks for this post. Do you know if it’s possible to add a private product in the cart ?