WooCommerce AJAX add to cart – Step-by-Step Tutorial
Some weeks ago we talked about how to add the cart function programmatically to boost your sales. Today, we’ll have a look at how to implement AJAX in the Add to cart button in WooCommerce products. This will improve user experience and the overall sales process, which will also help you optimize your store and increase your revenue.
Nowadays, if you want to run a successful store, it’s key that your site updates the cart dynamically. Otherwise, every time a user adds a product to the cart the page will reload making the buying process very slow and increasing the chances of customers dropping out. That’s why revamping your store with the WooCommerce AJAX add to cart function is a must to reduce cart abandonment and increase your sales.
In this guide, we’ll show you how to do it step-by-step.
Benefits of AJAX in WooCommerce
So to sum up, the benefits of using AJAX in your store are:
- Reduce server load and bandwidth
- Speed up the buying process
- Improve customer experience
- Reduce cart abandonment
- Increase conversion rates
Tutorial: WooCommerce AJAX add to cart
To apply the AJAX add to cart function in WooCommerce there are two options:
- With a plugin
- Coding it yourself
Let’s have a look at each method.
1) AJAX add to cart with a plugin
If you don’t have experience coding or you prefer an easy solution, using a plugin is an excellent choice. Simply download our AJAX add to cart WooCommerce plugin, install it and the software will do the rest.
AJAX add to cart for WooCommerce is one of the best plugins to add AJAX to the WooCommerce add to cart button. This tool allows shoppers to include single or variable products in their carts without having to reload the site every time. What’s even better is that it runs smoothly in 99% of WordPress themes and it doesn’t require any initial setup. Once you install it, it’ll be ready to go.
2) Code it yourself
Do you have some coding skills and prefer to customize your WooCommerce AJAX add to cart button? In this guide, we’ll show you how to do it step-by-step.
A) Install a child theme
The first thing you need to do is create a child theme. If you don’t have one, you can use a plugin. There are several of them so just pick the one you like best and install it in your store. Why should you install a child theme? Because if you directly customize the theme’s files, the next time you update the theme, the new files will replace your changes and all your customizations will be lost. However, if you customize the child theme, the modifications won’t be overridden.
B) Include JavaScript (JS) file
In the functions.php file of the child theme, include a JavaScript file by using the wp_enqueue_script hook. This is one of the most popular hooks that WordPress offers to customize websites. Let’s have a look at the script that includes the ajax_add_to_cart.js file below:
function ql_woocommerce_ajax_add_to_cart_js() { if (function_exists('is_product') && is_product()) { wp_enqueue_script('custom_script', get_bloginfo('stylesheet_directory') . '/js/ajax_add_to_cart.js', array('jquery'),'1.0' ); } } add_action('wp_enqueue_scripts', 'ql_woocommerce_ajax_add_to_cart_js');
With the conditional if (function_exists(‘is_product’) && is_product()) in line 2, you make sure that the JQuery is only applied on a product page.
C) Create a JS file
Once you’ve done that, create the file you included in the previous step. Just go to your cPanel and then to the child theme folder. After that, follow the route wp_content /themes/ folder. There, create a new folder in the child theme called js, and then a file inside it with the same name you used in the hook ajax-add-to-cart.js. Keep in mind that this step also works even if you use an FTP client. If your child theme already has a JS folder, you can use it without creating a new one.
D) The JQuery/JS file
The next step is to work on the JQuery file that you’ve uploaded in your child theme. That file is empty so you need to add scripts. First, prevent the add to cart button from reloading the page with the following script:
$('.single_add_to_cart_button').on('click', function(e) { e.preventDefault(); });
Please note that we use the $(‘.single_add_to_cart_button’) selector to trigger the AJAX call when the button is clicked. You must understand this because all the following script will go inside this function.
E) JQuery WooCommerce AJAX add to cart on single products
So the full JQuery script for AJAX add to cart on single products is:
jQuery(document).ready(function($) { $('.single_add_to_cart_button').on('click', function(e){ e.preventDefault(); $thisbutton = $(this), $form = $thisbutton.closest('form.cart'), id = $thisbutton.val(), product_qty = $form.find('input[name=quantity]').val() || 1, product_id = $form.find('input[name=product_id]').val() || id, variation_id = $form.find('input[name=variation_id]').val() || 0; var data = { action: 'ql_woocommerce_ajax_add_to_cart', product_id: product_id, product_sku: '', quantity: product_qty, variation_id: variation_id, }; $.ajax({ type: 'post', url: wc_add_to_cart_params.ajax_url, data: data, beforeSend: function (response) { $thisbutton.removeClass('added').addClass('loading'); }, complete: function (response) { $thisbutton.addClass('added').removeClass('loading'); }, success: function (response) { if (response.error & response.product_url) { window.location = response.product_url; return; } else { $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]); } }, }); }); });
F) The PHP script
Afterward, you need the PHP handler. The best way is to use some of the WooCommerce filter hooks to build your add to cart function. This time you’ll do it using AJAX. Simply copy and paste the following script in the functions.php file of the child theme below the previous script we used to include the JS file.
add_action('wp_ajax_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart'); add_action('wp_ajax_nopriv_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart'); function ql_woocommerce_ajax_add_to_cart() { $product_id = apply_filters('ql_woocommerce_add_to_cart_product_id', absint($_POST['product_id'])); $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']); $variation_id = absint($_POST['variation_id']); $passed_validation = apply_filters('ql_woocommerce_add_to_cart_validation', true, $product_id, $quantity); $product_status = get_post_status($product_id); if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) { do_action('ql_woocommerce_ajax_added_to_cart', $product_id); if ('yes' === get_option('ql_woocommerce_cart_redirect_after_add')) { wc_add_to_cart_message(array($product_id => $quantity), true); } WC_AJAX :: get_refreshed_fragments(); } else { $data = array( 'error' => true, 'product_url' => apply_filters('ql_woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id)); echo wp_send_json($data); } wp_die(); }
That’s it! You’ve just created your WooCommerce AJAX add to cart button! But how do you know that you’ve done everything correctly? You can check it easily. When you click on the add to cart button, the product should be added to the cart without reloading the page.
Conclusion
All in all, if you want to optimize your store, the WooCommerce AJAX add to cart function is a must. The easy way to apply it is by using the AJAX add to cart WooCommerce plugin. However, if you have coding skills, you can code AJAX add to cart yourself with a child theme and a bit of PHP as described above.
Both options are excellent so choose the one that better suits your needs and skills. This will help you improve user experience and increase your conversion rates. Please let us know your thoughts in the comments section below.
Finally, for more guides about WooCommerce, we recommend you check out our guides on how to add WooCommerce products and how to create default product attributes in WooCommerce.
38 Comments
Add comment Cancel reply
You must be logged in to post a comment.
Hi there,
Is there a way to exclude a specific product from the Ajax Add To Cart code?
I’ve tried adding:
if ( $( “.product” ).hasClass( “post-1651” ) ) { return false; }
To the js file without any success, any help would be very much appreciated!
Kind regards,
JP
Hello, you can exclude the script in PHP global $post, if $post->ID != 1651
Hello!
Awesome!
Err… sorry where in the PHP file should I place this?
Thank you so much for your help!
Kind regards,
JP
Hello Jhon
Go to your theme or child theme folder and edit the functions.php file
Hello,
Thank you so much, but I need to display thumb variation how can I do it ?!
Kind Regards
Hello mate
I’m afraid is not possible to display thumbnail inside a button
Hi there,
Awesome post. Is there any way to feature the product variation attributes in the cart page? As it happens when the ajax add to cart button is not enabled.
Kind Regards.
Esteban.
Hello Esteban
I’m not sure what you’re asking, can you share screenshot?
Hi
Thank you very much,
I prefert to use $(‘form.cart’) selector to trigger the AJAX call when the form is submit.
So the Quantity value is verified with attribute step, min or max.
This is only work in the self product page, how can I do to work in my entire website.
Thanks 🙂
Hello Renato
Try by removing this conditional login
if (function_exists(‘is_product’) && is_product())
Would it be possible to add two products with different variation ids at the same time? Right now it seems like the cart only updates when clicking on it. E.g. when I add variation 1 with a quantity of 2 and variation 3 with a quantity of 4, variation 1 gets added with a quantity of 4.
hello mate, I’m afraid it’s not possible with this script
Hi, thanks for your quick reply. How unlucky.. I’ll try to find another way then..
you’re welcome, please share it here if you find it
kind regards
Hi,
Many thanks for this easy-to-follow tutorial.
Tried it but ran into the following problems: clicking add to cart currently does nothing for me and I’m getting an “Uncaught ReferenceError: wc_add_to_cart_params is not defined” in my chrome console.
Any idea why this might be?
Many thanks in advance,
Alex
Hi Alex, you’re welcome !
This could be related to WP theme you are using.
It should work without issues with StoreFront.
Cheers
Hi,
Used plugin but it is workig o product detail. Not workig o category/shop page. Please suggest solutio for it.
Hello mate, the plug is only available for product pages
You can activate native woocommerce ajax add to cart function in archive pages
Kind regards
Thank you so much
Hi,
Thanks a lot for this code, it’s working perfectly.
However, i had to do a small adaptation in my case.
Maybe it could be useful for others.
I added 3 variations on my products: One is used to calculate different prices.
The two others are used only as “free/embeded” options: price won’t change with those.
In this case, we have to get selected attributes from field directly.
Then we use them to add a fourth parameter to add_to_cart method : “$variation_datas”.
Example for one attribute:
JS:
1) Adding selected option to vars
attribute_key = $form.find(‘select[id=attribute-key] option:selected’).val() || ‘default value’,
2) Adding it to datas below.
PHP:
1) Grabing passed attribute and store it in an array
$no_price_att = $_POST[‘attribute_key’];
$variation_data = array(
‘attribute_[key]’ => $no_price_att,
);
Repeat it for as many attributes as you want.
And again thanks you for this code.
Great, thanks a lot for the useful info
Thank you very much, I just change
$(‘.single_add_to_cart_button’).(‘click’, function(e)
to
$(‘form.cart’).(‘submit’, function(e)
I don’t know how to make notices appears (success, error…), do you have an idea ?
Thank you !
You’re very welcome !
I’m afraid that you will need to extend the JS file to display notices also with AJAX.
A simple solution would be just inserting an alert(‘success’); or alert(‘failure’) within JS conditional
We have a more catalog style approach to our web store, is there a way to just trigger the add-to-cart action once the user clicks the product image? (without having to click on an actual ‘button’) Just curious. Thanks.
Hello Ron
I believe you could make your image a link and edit the JQuery selector
$('.single_add_to_cart_button')
to your image link selector. But this is not tested.Please, let us know if you could achieve it
Cheers !
Hello
I have done as you described but no changes(((
What I have done wrong
Hi Arthur.
Are you seeing some kind of error?
Check the browser console also
what is the do_action(‘ql_woocommerce_ajax_added_to_cart’, $product_id); ?
hello mate, its a wordpress hook, please check https://developer.wordpress.org/reference/functions/do_action/
https://quadlayers.com/woocommerce-ajax-add-to-cart/#comment-49994
If you have problem with wc_add_to_cart_params you can add php script:
add_action(‘wp_enqueue_scripts’, ‘myAjax_data’, 98);
function myAjax_data()
{
wp_localize_script(
‘theme-add-to-cart’,
‘wc_add_to_cart_params’,
array(
‘ajax_url’ => admin_url(‘admin-ajax.php’)
)
);
}
Hello
I am using this amazing code and thanks for that, I have 1 issue:
I have product with 2 variation:
1. color
2. size
when I try to add to cart after i seleced the color and the size in my cart page I dodnt see the product I see this error: Size is a required field
Hi ray. I’m happy that you liked our post!
But I’m afraid that you’ll need to extend the script to support variable products.
Check this thread -> https://stackoverflow.com/questions/27270880/add-a-variation-to-cart-using-ajax-woocommerce-api/27278035#27278035
Cheers !
ЦАР СИ МОЙ ! Евала, CHEERS !
Great post, thanks a lot. Has anyone figured out a way to show the WooCommerce notices. I know how to display a notice from the js but I don’t know how to receive the specific notices (“we have X in stock and you already have Y in your cart”, “Product successfully added to cart” etc. ) in the js code. Thanks
Thank you so much!
Is there a way for the cart menu to appear only if it detects that there are 4 products in the cart?
Sorry, but did you even test this code? It simply can’t work properly in the form in which it is placed in your article. For example, filter apply_filters(‘ql_woocommerce_add_to_cart_validation’) does not exist.
But there is filter apply_filters(‘woocommerce_add_to_cart_validation’).
All hooks and filters in your PHP code have this error.
Please, correct your code because you are misleading many people and wasting their time.
The ajax is already working but I want to make spining the add to cart when I press it, How can I do it, please?