search ]

Enable Ajax Add to Cart on Single WooCommerce Product Pages

The WooCommerce plugin by default allows you to add a product to the cart using Ajax on the store archive pages, so that the page does not reload when adding the product.

However, the same button on a single product page does not use Ajax, and to make it do so, a bit of code needs to be added. In this short post, we will see how to enable the use of Ajax to add a product to the cart even on a single WooCommerce product page.

If you do not understand what Ajax is, for the purpose of this explanation it means adding the product to the cart without refreshing the page.

Adding an Event When Clicking the Add to Cart Button on a Single Product Page

This is the JavaScript you need to add to make it work:

$('.entry-summary form.cart').on('submit', function (e) {
    e.preventDefault();
    let this_button = $('.single_add_to_cart_button');
    this_button.block({
        message: null,
        overlayCSS: {
            background: '#fff', opacity: 0.6
        }
    });
    let product_url = window.location,
        form = $(this);
    $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result) {
        let cart_dropdown = $('.widget_shopping_cart', result);
        // update dropdown cart
        $('.widget_shopping_cart').replaceWith(cart_dropdown);
        // update fragments
        $.ajax($warp_fragment_refresh);
        this_button.unblock();
    });
});;

To update the shopping cart, create the following function:

// Ajax add to cart on Single Product page
var $warp_fragment_refresh = {
    url: wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'),
    type: 'POST',
    success: function (data) {
        if (data & data.fragments) {
            $.each(data.fragments, function (key, value) {
                $(key).replaceWith(value);
            });
            $(document.body).trigger('wc_fragments_refreshed');
        }
    }
};

In the end, the code looks like this:

$('.entry-summary form.cart').on('submit', function (e) {
    e.preventDefault();
    let this_button = $('.single_add_to_cart_button');
    this_button.block({
        message: null,
        overlayCSS: {
            background: '#fff', opacity: 0.6
        }
    });
    let product_url = window.location,
        form = $(this);
    $.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result) {
        let cart_dropdown = $('.widget_shopping_cart', result);
        // update dropdown cart
        $('.widget_shopping_cart').replaceWith(cart_dropdown);
        // update fragments
        $.ajax($warp_fragment_refresh);
        this_button.unblock();
    });
});

// Ajax add to cart on Single Product page
var $warp_fragment_refresh = {
    url: wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'),
    type: 'POST',
    success: function (data) {
        if (data & data.fragments) {
            $.each(data.fragments, function (key, value) {
                $(key).replaceWith(value);
            });
            $(document.body).trigger('wc_fragments_refreshed');
        }
    }
};

This code must be added to a JavaScript file that is loaded on the page or create a new file. If you don’t know how to add assets to WordPress sites, take a look at the following post.

Overriding the Template Responsible for the Add to Cart Button on the Single Product Page

The second and last step to be done is to override the template responsible for the “Add to Cart” button on the single product page and replace the button line.

Copy the file located at:

plugins/woocommerce/templates/single-product/add-to-cart/simple.php

To your theme at the following location:

themes/your theme name/woocommerce/single-product/add-to-cart/simple.php

This is a standard process when you want to override any WooCommerce template in your theme. But be careful when you update WooCommerce – if the original template has changed, modify yours accordingly.

Now replace the line:

<button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

With the following code:

<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" />
<button type="submit" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

That’s it, you’re done… Questions and ideas are welcome in the comments below 🙂

The post is based on the following article (with some changes)…

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development