How to add products to your WooCommerce cart with PHP and ajax

This tutorial explains how to add products to your Woocommerce cart programatically with PHP and ajax.

Add to cart in WooCommerce via URL

In case you’re looking for a simple solution without ajax and PHP, there is a custom add to cart URL in WooCommerce:

The quantity parameter is optional, the default value is 1. The add-to-cart parameter is required and contains the product ID for simple products and the variation ID for variable products.

Add to cart in Woocommerce PHP method

There is a prebuilt method in WooCommerce to handle add to cart programatically:

The only required paramater is the $product_id, in case of variations you should also set your $variation_id and the $variation variable with the variation attributes:

For example to add a product automatically in your cart create a custom method in your functions.php:

Don’t forget to hook the method to a WooCommerce action of your choice.

Add to cart in WooCommerce with ajax and PHP

The advanced solution is to use ajax and PHP. There is a method predefined in WooCommerce. Let’s create a custom method in our functions.php to add a product with the ID of 65 to our WooCommerce cart via ajax:

As the last step you will need to include a small javascript code. This part depends on what you want to achieve. In the example I’m going to include a short javascript code on every page and the add to cart is triggered on button click. Make sure the action parameter in your ajax call matches the WordPress action name without the wp_ajax or wp_ajax_nopriv prefix (add_my_custom_product_to_cart_action and wp_ajax_add_my_custom_product_to_cart_action in our example):

Happy coding!

0 0 vote
Article Rating
Notify of
Inline Feedbacks
View all comments