search ]

Enable Ajax Add to Cart on Single WooCommerce Product Pages

By default, WooCommerce uses AJAX to add products to the cart on archive pages without a page reload. However, the add-to-cart button on single product pages triggers a full page refresh.

This guide shows how to enable AJAX add-to-cart on single WooCommerce product pages using custom JavaScript and a template override.

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.

Note: Starting with WooCommerce 7.8, cart fragments are disabled by default and only load when a Cart Widget is rendered on the page. Make sure your theme includes a cart widget or that the wc-cart-fragments script is enqueued. Also note that this approach works for simple products. Variable products require additional handling for attribute selection.

Step 1: AJAX Add to Cart JavaScript

First, define the fragment refresh configuration, then attach the form submit handler. Make sure to enqueue this script with wc-cart-fragments as a dependency:

// Fragment refresh configuration
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');
        }
    }
};

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

Add this code to a JavaScript file and enqueue it in your theme with wc-cart-fragments as a dependency:

wp_enqueue_script( 'ajax-add-to-cart', get_stylesheet_directory_uri() . '/js/ajax-add-to-cart.js', array( 'jquery', 'wc-cart-fragments' ), '1.0', true );

Step 2: Override the Add to Cart Template

The second step is to override the template responsible for the add-to-cart button. This moves the add-to-cart value to a hidden input so the form submission can be intercepted by JavaScript.

Copy the file from:

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 the standard process for overriding WooCommerce templates. After each WooCommerce update, compare your overridden file with the original to ensure compatibility. The template version is noted at the top of each file.

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>

FAQs

Does this work with variable products?
This implementation is designed for simple products. Variable products require additional handling to serialize the selected attribute values (like size and color) and use the variable.php template instead of simple.php. The JavaScript form serialization captures the data, but you would need to override the variable product template as well.
Why do I need to override the WooCommerce template?
The default add-to-cart button includes the product ID in its name attribute, which causes a standard form submission (full page reload). By moving the product ID to a hidden input field, the form can be intercepted by JavaScript for AJAX submission while still passing the required data to WooCommerce.
What are WooCommerce cart fragments?
Cart fragments are small HTML pieces that WooCommerce uses to update the cart widget, cart count, and cart totals without a full page reload. The get_refreshed_fragments endpoint returns updated HTML for all registered fragments, which are then swapped into the page via JavaScript. Since WooCommerce 7.8, the fragments script only loads when a cart widget is present on the page.
Will my template override break after a WooCommerce update?
Possibly. WooCommerce may update its templates in major releases. After updating, check the WooCommerce status page (WooCommerce > Status > Templates) to see if any of your overridden templates are outdated. If so, compare your version with the new original and apply the necessary changes.
The cart count is not updating after adding a product. What should I check?
Make sure the wc-cart-fragments script is enqueued as a dependency of your JavaScript file. Verify that your theme includes a cart widget (required since WooCommerce 7.8 for fragments to load). Also check that caching plugins are not serving a cached version of the cart fragments endpoint.

Summary

Enabling AJAX add-to-cart on single WooCommerce product pages requires two steps: a JavaScript handler that intercepts the form submission and refreshes cart fragments, and a template override that moves the product ID to a hidden input field.

Remember to enqueue your script with wc-cart-fragments as a dependency, and always check your template overrides after WooCommerce updates. For more on customizing WooCommerce behavior, see our guide on WooCommerce hooks.

Join the Discussion
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 official logo