How to enable Ajax add to cart on WooCommerce product & archive pages [2021]

by | Mar 15, 2021 | Divi Tutorials, WordPress Tutorials | 1 comment

WooCommerce is the most popular e-commerce platform out there. This plugin is amazing and allows you to sell anything online. WooCommerce has tons of features, but it also lacks some essential conversion tools.

If you want to sell online, you need to make the purchase process as easy as possible for your customers. When your clients select the product they want and click the “add to cart” button, WooCommerce reloads the entire page to add the product to the cart, which is not ideal for conversions!

In this tutorial, you will learn how to enable ajax add to cart on single product and archive (categories, tags & shop ) pages.

What is Ajax?

Simply, it is performing actions without reloading the page! In our case, adding the product to the cart without the need for reloading the entire website.

This is a beneficial technique as it makes the purchase easy for customers. It also very quick and reduces the load on the server because only a tiny part of the page gets updated.

Enable Ajax add to cart on WooCommerce archive pages

Archive pages are the product listing pages like categories, tags, and the shop page. To enable ajax add to cart on these pages, all you have to do is to go to your WordPress admin dashboard -> WooCommerce -> Settings -> Products tab.

Enable Ajax add to cart on WooCommerce archive pages

Check the option “Enable AJAX add to cart buttons on archives”.

That’s it!

Enable Ajax add to cart on single product page

This one is not direct as on archive pages because WooCommerce itself does not provide the option for it.

There are two ways to achieve this ajax add to cart on single product pages; use a plugin or do it yourself using custom code.

WooCommerce Builder For Divi Plugin

If you are using Divi theme and WooCommerce together, then our WooCommerce Builder For Divi plugin allows you to add products to the cart via ajax with a click of a button. This option is available in two modules; the add to cart module and the product summary module.

Enable Ajax add to cart on single product page

This is great because you can enable this option for individual products, products based on their category, or all products at once.

This works for simple, variable, and grouped products as well. It even works with 3rd party plugins like WooCommerce Booking and WooCommerce product Add-ons.

Ajax add to cart for WooCommerce by QuadLayers

It is a very simple plugin that works. The plugin is free and available on the WordPress plugin directory, you can download it from here. The plugin works for simple and variable products.

Ajax add to cart using custom code

This is the most advanced way to do it. This part is for developers, not regular people. Don’t use his method if you are not familiar with custom PHP or Javascript or are afraid to corrupt your website.

We will make use of the WooCommerce built-in Ajax, so make sure you enable the ajax on archive pages as explained above.

Please, test this first on a local WordPress installation or on a staging copy of your website just to keep it safe from errors. If everything is working fine, you can push the changes to the live website.

Let’s dive right in.

Step 1: get a child theme

You don’t need to modify your main theme’s files, because any changes you make to the main theme will be gone immediately after updating the theme to a new version.

So, we will use a child theme for that, If you don’t have a child theme, you can easily generate one for free using this tool.

Step 2: add the Javascript

1. Create a folder into your child theme’s main folder and call it js

2. In the js folder, create a new file and call it ajax-add-to-cart.js

3. Add the following code to this file.

jQuery(function($){

    /* global wc_add_to_cart_params */
    if ( typeof wc_add_to_cart_params === 'undefined' ) {
		return false;
    }
  
    $(document).on('submit', 'form.cart', function(e){
        
        var form = $(this),
            button = form.find('.single_add_to_cart_button');
        
        var formFields = form.find('input:not([name="product_id"]), select, button, textarea');

        // create the form data array
        var formData = [];
        formFields.each(function(i, field){

            // store them so you don't override the actual field's data
            var fieldName = field.name,
                fieldValue = field.value;

            if(fieldName && fieldValue){

                // set the correct product/variation id for single or variable products
                if(fieldName == 'add-to-cart'){
                    fieldName = 'product_id';
                    fieldValue = form.find('input[name=variation_id]').val() || fieldValue;
                }

                // if the fiels is a checkbox/radio and is not checked, skip it
                if((field.type == 'checkbox' || field.type == 'radio') && field.checked == false){
                    return;
                }

                // add the data to the array
                formData.push({
                    name: fieldName,
                    value: fieldValue
                });                
            }

        });

        if(!formData.length){
            return;
        }
        
        e.preventDefault();
        
        form.block({ 
            message: null, 
            overlayCSS: {
                background: "#ffffff",
                opacity: 0.6 
            }
        });

        $(document.body).trigger('adding_to_cart', [button, formData]);
  
        $.ajax({
            type: 'POST',
            url: woocommerce_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'),
            data: formData,
            success: function(response){
                if(!response){
                    return;
                }

                if(response.error & response.product_url){
                    window.location = response.product_url;
                    return;
                }
                
                $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, button]);
            },
            complete: function(){
                form.unblock();
            }
        });
  
      return false;
  
    });
});

Step 3: add the PHP

For the above code to work, we need to tell WordPress about it.

So, in the main folder of your child theme, you will find a file called functions.php. Open this file and add the following code at the very end of the file but be careful, if the file ends with ?> remove it and then add the code.

/**
 * Enable ajax add to cart for WoCommerce products
 * @author DiviKingdom.Com
 * @version 1.0.0
 */
function DiviKingdom_wc_single_ajax_add_to_cart(){
    if(function_exists('is_product') && is_product()){
        wp_enqueue_script('dk-wc-add-to-cart', get_stylesheet_directory_uri() . '/js/ajax-add-to-cart.js', array('jquery'), false, true);
    }
}
add_action('wp_enqueue_scripts', 'DiviKingdom_wc_single_ajax_add_to_cart');

Step 4: test the code!

This custom code works with simple, variable, and grouped products. It also works with 3rd party plugins like WooCommerce Booking and Add-ons. If it works for you, congratulations! But if it doesn’t, make sure you followed all the steps above.

If it does not work after that, you may consider using a plugin or hire a developer to do it for you.

Let me know if it works for you in the comments and if you want to see other tutorials like this!

By Abdou

My name is Abdelfatah Aboelghit, a PHP developer from Egypt and my friends call me Abdou!
Here I write and develop products about Divi Theme.

More Article

1 Comment

  1. Leah

    Thanks. This is just what I needed. I added your code, and everything is great! Question- any way I can have that after the item is added to cart, instead of a button coming up that says ‘view cart’, I want 2 buttons- 1 that says view cart, and another custom url.
    How can I do this?

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Shop Tabs Plugin

A must-have plugin for Divi & WooCommerce.

Read More

Divi Theme

The Best Theme For WordPress. 

Read More

Pin It on Pinterest

Share This