Using custom code

So you’re a developer who wants to add a WooCommerce AJAX add to cart button to your website? Now we’re going to teach you step-by-step how to accomplish it.

Step 1: Install a child theme

First and foremost, you must build a child theme. You can accomplish this with a variety of plugins, so pick your favorite, install it, and utilize it to create your child theme.

If you’re wondering why you sho

uld utilize a child theme instead of the main theme, consider the following. The reason for this is that if you alter the theme’s files directly, the new files will overwrite your changes, and all of your changes will be lost the next time the theme is updated. Changes made to the child theme, however, will not be overwritten.

Step 2: Add the Javascript (JS) file

Add a JavaScript file to the child theme’s functions.php file using the wp_enqueue_script hook. This is one of the most common hooks for customizing websites that WordPress provides. Now let’s look at the script, which contains the ajax-add to-cart.js file:

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');

It’s worth noting that in line 2 of the conditional if (function_exists(‘is_product’) && is_product()), you must apply the JQuery on the product page only.

Step 3: Create a Javascript file

Create the file that you inserted in the previous step after that. Simply go to the child theme folder in your cPanel. Then go to the /themes/ folder in the wp content folder. Create a new folder entitled js in the child theme, as well as a file with the same name as the hook ajax-add-to-cart.js, in this case.

Remember that you can accomplish this even if you’re using an FTP client.

Instead of creating a new JS folder, you may utilize one that already exists in your child theme.

Step 4: Add scripts to the JQuery file

This step requires you to work on the JQuery file you recently uploaded to your child theme. Because that file is currently empty, you must add scripts to it.

First and foremost, you must disable the add to cart button’s ability to reload the website. Add the following script to accomplish this:

Keep in mind that the AJAX request is initiated by the $(‘.single add to cart button’) selector when the add to cart button is pressed. Now you must add the following JQuery script to each single product for AJAX add to cart:

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]);
                } 
            }, 
        }); 
     }); 
});

Step 5: Add the PHP

After that, you’ll require the PHP handler. The simplest way to build your add to cart functionality is to use some WooCommerce filter hooks. You’ll repeat the process, but this time with AJAX.

Simply copy and paste the following script below the previous script we used to add the JS file to the child theme’s functions.php 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();
        }

Step 6: Test the code

By clicking the add to cart button, you may check whether you entered the code correctly. You’ve successfully developed your ** WooCommerce AJAX add to cart button** if the product can be added to the cart without refreshing the page.

However, if this is not the case, make sure you go over all of the instructions again.

If it still doesn’t work after that, use the first way of utilizing a plugin or contact a developer for assistance.

Final Words

Overall, if you want to improve your online business, you should include the WooCommerce AJAX add to cart button to your WooCommerce product page. You may achieve this by using the WooCommerce AJAX add-to-cart plugin or by utilizing custom scripts.

Categorized in: