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:
* Add items to cart on loading checkout page.
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 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.