Often when building your WooCommerce store you run into having to add to cart in unfamiliar ways.
This may happen when you have a custom offer page, for example. Or you might just want to avoid having a regular, long, checkout funnel. Some stores just don’t need all the options a regular store does and, usually, the easier it is for customers to purchase, the better.
Here’s a straightforward approach extracted from the actual WooCommerce function:
You can add this to your theme’s footer for example ( just before the closing body tag
One thing to keep in mind is that if you include the code inside another function it won’t be globally accessible anymore.
The cool part of this is that if you have a properly-built theme the cart will also update without having to reload the page.
Things to note:
- The function makes an Ajax call so it’s not instant ( synchronous ). Even though it feels like that on a good connection.
- If you want to add visual feedback you’ll need to modify the
$.postcall to add a callback.
- Read the comments in the code and remove the parts which aren’t necessary for you.
- If you want specific help, ask in the comments! I’m happy to help if I can.
Making sure the function works
If you want to quickly test this function, after adding it to your site, just open the console and call it directly. I’ve set up a quick example site using WooCommerce’s default theme Storefront here: https://wcplayground.mircian.com/
To see the function in action, go to the link above, open the Developer console, write
m_wc_add_to_cart( 42 ) and press Enter. You’ll notice that the top right cart in the header is immediately updated.
You’ll also be able to use this for variations, if you know the variation id. Try using the id 66 in the example above and check out the cart.
If the function doesn’t work in your setup, make sure the function is available globally. Also check if
wc_add_to_cart_params is available, otherwise the function won’t do anything.
Add to cart programmatically using PHP
It’s easier to modify the cart on the PHP side. For most setups you’ll still need to call this from the frontend using an Ajax call or submitting a form.
A couple of concepts to keep in mind for this:
- WooCommerce interactions should be made using the
WC()function which should be available anywhere. This allows you to access the WooCommerce instance while ensuring future compatibility of your code.
- You won’t be able to use all functionality if you don’t use the right hook. A safe bet is to use
woocommerce_initwhich ensures all components were loaded.
With that in mind, adding to the cart is just a matter of calling:
WC()->cart->add_to_cart( $product_id, $quantity );
You can even leave out the quantity as it will default to 1.
WC()->cart->add_to_cart( 45 ); and the right variation will be added.