How to successfully implement ajax add to cart in WooCommerce
Full-page reloads can disrupt the shopping flow and frustrate your customers. In this in-depth tutorial, I'll show you three different methods (the default settings, plugins, and custom code) to enable the WooCommerce AJAX add to cart feature in your online store.
If you're looking to add an AJAX add to cart function to your WooCommerce store, this guide is for you. Here, we'll explore three methods that you can use to enable AJAX add to cart in WooCommerce:
- WooCommerce's built-in AJAX add to cart setting.
- The best WooCommerce AJAX add to cart plugins — AJAX add to cart for WooCommerce, WooCommerce Product Table, WooCommerce Bulk Variations, and WooCommerce Fast Cart.
- Custom javascript and PHP AJAX add to cart code snippets.
I'll also outline the pros and cons of each method, and answer common questions about adding the AJAX add to cart feature to WooCommerce.
Sounds good? Great, let's jump straight into it.
What is WooCommerce AJAX add to cart?
In WooCommerce, AJAX add to cart is a feature that enables customers to add products to their shopping carts without triggering a full-page reload.
Instead of refreshing the entire page whenever a customer adds an item to their cart, AJAX communicates with your website's server in the background to update the cart contents dynamically. The result? Reduced friction and a smoother and faster shopping process.
To illustrate how this works
Let's suppose you run an online clothing store. A customer is browsing on the T-shirt category page and they click the "Add to cart" button for one of the T-shirts.
Without AJAX
- Clicking "Add to Cart" would reload the entire page which can be a frustrating user experience.
With AJAX
- The selected t-shirt is added to their cart instantly without reloading or redirecting them to the cart page.
- The header cart icon updates to reflect the added item.
- A success message appears confirming the action.
How to enable WooCommerce's native AJAX add to cart feature
Out of the box, WooCommerce comes with an AJAX add to cart feature, which you can activate on Product Archive pages like Shop, Category, or Tag pages.
It performs the core AJAX function: if enabled, it triggers an AJAX request when a customer clicks the "add to cart" button, and the cart count updates instantly in the header.
Limitations of WooCommerce’s default AJAX add to cart setting
Even though it is functional out of the box, WooCommerce's default implementation has several limitations that can impact customers' shopping experience in your store. Here’s what I mean:
- It doesn't work on product detail pages. The default AJAX function is only enabled on Product Archive pages (e.g., Shop, Category, and Tag pages). If a customer clicks the add to cart button on single product pages, it will trigger a full-page reload.
- It doesn't support quantity selection. With the default AJAX system, customers can't choose product quantities directly on Archive pages. The "Add to Cart" button only adds a single unit of the product. So if, for example, a customer is browsing a grocery store’s Category page and wants to add three cartons of milk, they’ll need to either navigate to individual product pages to adjust the number of items or manually update the quantity in the cart after adding it. Both options introduce extra steps and friction to the shopping process.
- It doesn't work for variable products. Product variations, aka items with size, color, or other options, aren’t supported by default AJAX on Archive pages. Customers must navigate to product detail pages to select variation options before proceeding to checkout.
All in all, these limitations slow down the shopping process and can frustrate users looking to quickly complete their purchases. To fix these issues, many store owners prefer to use plugins or custom code to implement AJAX add to cart in their stores.
How to enable WooCommerce’s default AJAX add to cart setting
WooCommerce's built-in AJAX add to cart feature is disabled on Product Archive pages by default. Here's how to activate it:
- In your WooCommerce site's admin, navigate to WooCommerce → Settings → Products → General.
- Locate the "Add to cart behaviour" section and tick the “Enable AJAX add to cart buttons on archives” button.
- Scroll down the page and press the Save Changes button.
That's it! The buttons on your site's Shop, Category, and Tag pages will use AJAX to add products to the cart. Feel free to head to your site's front end to test it out.
The best WooCommerce AJAX add to cart plugins
WooCommerce’s default AJAX add to cart feature is a great starting point. However, if you'd like to get rid of more friction points in the customer journey, these plugins can help:
- AJAX add to cart for WooCommerce - Enables AJAX add to cart buttons on product detail pages in WooCommerce.
- WooCommerce Product Table - Replaces the default Shop and Category page layout with an AJAX-powered, conversion-boosting order form layout. Customers can quickly select products, adjust quantities, and choose variations without leaving the page.
- WooCommerce Bulk Variations - Lists variations in a user-friendly grid or matrix on product detail pages, complete with AJAX add to cart buttons.
- WooCommerce Fast Cart - Upgrades the default cart and checkout flow with a sleek, conversion-focused popup or modal cart with a built-in checkout, also powered by AJAX.
Let's take a more in-depth look at each plugin.
AJAX add to cart for WooCommerce
The AJAX add to cart for WooCommerce plugin takes WooCommerce's built-in features one step further. Used by more than 20,000 Woo stores and with multiple 5-star ratings, it adds the AJAX add to cart feature to single product pages in WooCommerce.
With this plugin, when customers add products (whether simple, variable, or grouped) to their shopping carts from their product detail pages, there won't be a full-site reload each time.
To use AJAX add to cart for WooCommerce, simply:
- Head to Plugins → Add New Plugin in your site's admin panel.
- Search for the AJAX add to cart for WooCommerce plugin by QuadLayers, then install and activate it.
That's it! Now you can head to product detail pages and test out the AJAX add to cart feature.
Note: AJAX add to cart for WooCommerce fixes the gap in WooCommerce's default AJAX add to cart function but that's it. There are no quality-of-life improvements. Also, it doesn't do anything else to boost your store's sales and conversion rates — for example, to enhance how products are presented to customers or remove friction from other parts of the customer journey.
That's where the other WooCommerce AJAX add to cart plugins on our list come in.
WooCommerce Product Table
WooCommerce Product Table is a powerful plugin that displays products in a table-like format and makes it easier for customers to browse, search, and purchase items.
Here's a brief overview of how it works:
WooCommerce Product Table upgrades WooCommerce's default store layout with quick product order forms, complete with AJAX add to cart buttons.
Customers select their desired products, variations, and quantities with the quick add to cart checkboxes. Then use the "Add Selected to Cart" buttons to add all the selected items to their carts — all powered by AJAX.
Granted, not every store might need to replace the default layout of WooCommerce's Shop and Category pages.
But if your store has a large product catalog (e.g., clothing retailers), targets a specific audience (e.g., wholesalers), or has a customer base that typically needs to compare and select multiple products quickly (e.g., auto parts retailers), the product table layout is a godsend.
It simplifies the ordering process, boosts conversion rates, and improves the overall user experience (UX).
WooCommerce Product Table's key features
- Customizable table layout. You can choose the columns and product data to be displayed in the table — name, price, image, SKU, stock status, custom fields, etc.
- AJAX-powered search and filters. Customers can filter products by categories, tags, attributes, or custom taxonomies. It is powered by AJAX which filters results instantly and shows relevant results.
- Support for product variations. Customers can select product variations (size, color, material, etc.) directly from the table and add them to the cart without opening their individual product pages.
- Bulk add to cart. Customers can select multiple products and add them to the cart in one click — super handy for wholesale and bulk-quantity orders.
- Sorting and pagination. It supports sorting by columns (e.g., price or stock status) and includes a pagination option. Sites with large product catalogs can easily keep the user interface clean and easy to navigate.
- Quick product details. It has a quick view or expand option built-in to show more product information without leaving the table.
Next steps: Click here to learn more about WooCommerce Product Table.
WooCommerce Bulk Variations
WooCommerce Bulk Variations presents multiple product variations in an easy-to-use table or grid format on WooCommerce product detail pages. Thousands of stores that sell products with several variations — think: clothing, accessories, sporting equipment, or wholesale goods — use it to make the ordering process simpler.
WooCommerce Bulk Variations' key features
- Variation grid display. Instead of dropdowns, this plugin shows variations in a grid or matrix format, where customers can easily see all combinations of attributes (e.g., size, color) at a glance. For example, in the image below, this clothing store has displayed a grid with "Size" (XS, S, M, L, XL) as rows and "Color" (Red, Green, Blue, Orange, Yellow) as columns.
- Bulk quantity selection. Customers can enter quantities for multiple variations directly in the grid. Then after selecting quantities for multiple variations, they can add them all to the cart with one click.
- Customizable content and display options. You can control which attributes are displayed and how the grid is styled. For example, if enabled, it can automatically pull descriptions, images, stock levels, and prices, and display them in the grid to give customers additional information for each variation.
- AJAX-powered add to cart buttons. WooCommerce Bulk Variations uses AJAX to dynamically update stock quantities, pricing, and availability within the grid or matrix to ensure a fast and smooth user experience. Plus, the variation grids are fully responsive and are easily usable across all device sizes.
Next steps: Click here to learn more about WooCommerce Bulk Variations.
WooCommerce Fast Cart
WooCommerce Fast Cart revamps WooCommerce's default checkout flow and replaces it with a simpler, conversion-focused process. Instead of customers having to actively search for the cart page to initiate checkout, it allows customers to view their cart and checkout without leaving the current page.
With WooCommerce Fast Cart, once customers add items to their cart from any page on your site, a pop-up or slide-in modal window appears. Customers can review their items, adjust quantities, or proceed to checkout without navigating away from the page.
WooCommerce Fast Cart's key features
- Quick cart with built-in checkout. It adds a modal popup or slide-in panel where customers can view their carts, make adjustments, and complete checkout without leaving the page they are on. This reduces the number of steps to check out and lowers cart abandonment rates.
- AJAX-powered cart updates. The fast cart updates dynamically when customers adjust quantities, remove products, or apply coupon codes — no full-page reloads.
- Compatibility with shipping and payment providers. It integrates with your WooCommerce store's shipping methods and payment gateways. This ensures that customers will see accurate order totals and can select their preferred payment method(s) within the cart to complete the purchase.
- Cross-sells and upsell integration. It allows you to display relevant cross-sell or upsell suggestions directly in the cart. For example, if a customer adds a smartphone, you can recommend related products like cases, screen protectors, and other accessories.
- Customizable design. You can customize the cart layout and easily adjust colors and fonts to match your store’s branding and create a seamless ordering experience.
Next steps: Click here to learn more about WooCommerce Fast Cart.
WooCommerce AJAX add to cart code snippet
If you're confident in your development skills and prepared to maintain the code, I've got PHP and JavaScript snippets for you to add custom AJAX add to cart buttons to your site.
(If not, skip this section and use the options shared above. Custom code isn’t automatically updated with new WooCommerce releases. If relevant WooCommerce hooks or scripts change during an update, this feature could stop working. Not to mention, a small error in the code could break your site or disrupt the user experience 🙃).
Without further ado, here are the steps to enable the AJAX function on the WooCommerce single product page without triggering a full-page page reload.
1. Create the JavaScript File (ajax-add-to-cart.js) in your child theme's /js folder
It can sometimes also be located in your child theme's /assets folder. If the /js folder doesn't exist at all, create one and make sure you write the exact path to this js file when enquing it in php in step 2.
This file contains the code that listens for the "Add to Cart" button click and prevents the default page reload. Instead, it triggers an AJAX call to add the product to the cart, updating the cart without reloading the page.
Code snippet:
jQuery(document).ready(function ($) {
// Trigger on the "Add to Cart" button click
$("form.cart").on("submit", function (e) {
e.preventDefault(); // Prevent form submission
var $this = $(this),
product_id = $this.find("input[name=add-to-cart]").val(),
quantity = $this.find("input.qty").val() || 1,
variation_id = $this.find("input[name=variation_id]").val() || 0,
data = {
action: "woocommerce_ajax_add_to_cart",
product_id: product_id,
quantity: quantity,
variation_id: variation_id,
};
// Show a loading spinner (optional)
$this
.find(".single_add_to_cart_button")
.after('<span class="loading">Loading...</span>');
// AJAX call
$.ajax({
type: "POST",
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
if (response.error && response.product_url) {
window.location = response.product_url;
} else {
// Trigger WooCommerce's added_to_cart event and update fragments
$(document.body).trigger("added_to_cart", [
response.fragments,
response.cart_hash,
]);
// Optionally: Remove the loading spinner and show success message
$(".loading").remove();
alert("Product added to cart!");
}
},
error: function () {
$(".loading").remove();
alert("There was an error. Please try again.");
},
});
});
});
2. Enqueue the JavaScript
Open your child theme's functions.php file and use wp_enqueue_script()to load the JavaScript code responsible for handling the AJAX request on your single product pages.
Code snippet:
function custom_woocommerce_ajax_add_to_cart_js() {
if (is_product()) { // Only load the script on single product pages
wp_enqueue_script(
'ajax-add-to-cart',
get_template_directory_uri() . '/assets/js/ajax-add-to-cart.js',
array('jquery'),
null,
true
);
}
}
add_action('wp_enqueue_scripts', 'custom_woocommerce_ajax_add_to_cart_js');
Modify this path ('/assets/js/ajax-add-to-cart.js') according to where you created your js file.
3. Handle the AJAX Request with PHP
In your child theme's functions.php file, define a function that processes the incoming AJAX request.
This PHP function adds the product to the WooCommerce cart and sends back updated cart fragments (e.g., the cart total or the number of items) to refresh the cart section in the user's view.
Code snippet:
function custom_ajax_add_to_cart_handler() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = empty($_POST['variation_id']) ? 0 : absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id)) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
// Return fragments for updating the cart
WC_AJAX::get_refreshed_fragments();
} else {
// If there's an error, return the product URL for redirect
wp_send_json(array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id),
));
}
wp_die();
}
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'custom_ajax_add_to_cart_handler');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'custom_ajax_add_to_cart_handler');
4. Ensure cart fragments are refreshed
WooCommerce automatically handles refreshing the cart when products are added via AJAX. However, if the mini-cart or cart fragments are not updating after the product is added, make sure WooCommerce's wc-cart-fragments script is enabled.
In your child theme's functions.php, add this code:
function enqueue_wc_cart_fragments() {
if (is_product()) {
wp_enqueue_script('wc-cart-fragments');
}
}
add_action('wp_enqueue_scripts', 'enqueue_wc_cart_fragments');
FAQs about WooCommerce AJAX add to cart
Here are answers to common questions about adding AJAX add to cart buttons in WooCommerce.
How does AJAX add to cart impact site performance?
Here's how the AJAX add to cart feature can impact the performance of your WooCommerce site.
- Reduced server load from full-page reloads. AJAX eliminates the need for full-page reloads. This is important because each time a page reloads fully, the server has to process requests for all static assets, including CSS, JavaScript, and images. Without AJAX, every “Add to Cart” action would trigger a page reload, which forces the server to re-render the entire page repeatedly. With AJAX, only the relevant cart data is processed, which significantly lowers server demand and speeds up interactions. This reduces the amount of data that needs to travel between the server and the user's device by 56%, which means quicker responses and less strain on your website's bandwidth.
- Enhanced site usability. In addition to under-the-hood speed enhancements, AJAX makes the shopping experience feel more intuitive and responsive on the front end. Customers receive immediate feedback when they add an item to their cart — whether it’s an updated mini cart, a notification, or a cart total adjustment. This eliminates confusion and keeps them engaged in the shopping experience.
What are the benefits of adding WooCommerce AJAX add to cart?
In addition to technical improvements, here's how enabling AJAX add to cart benefits your bottom line.
It lowers bounce rates
As a WooCommerce store owner, you know firsthand that every second counts in e-commerce. Long delays caused by page reloads or clunky interactions can frustrate customers and cause them to bounce off without completing their purchases.
Implementing AJAX keeps the ordering experience smooth and reduces the likelihood of customers abandoning their carts.
It increases conversions
The more effortless the shopping process, the more likely that customers complete their purchases.
AJAX not only speeds up the ordering process with instant cart updates but also provides clear visual feedback so customers can take further steps, like adding more products to their cart or initiating the checkout process. This leads to higher conversion rates by keeping customers engaged until checkout.
It improves user experience (UX)
Without AJAX, adding a product to the cart from Product Archive pages often takes the customer back to the top of the page.
With Ajax, when customers add products to their cart, they won’t have to wait for the page to reload or navigate back to where they were. AJAX keeps them right where they are so they can continue browsing and adding products without losing their place. This saves time and improves your site's user experience (UX).
How can I implement AJAX add to cart without a plugin?
There are two ways to add the AJAX function to your WooCommerce store without relying on a plugin:
- Using WooCommerce's native AJAX add-to-cart feature which you can enable for Product Archives like Shop, Category, or Tag pages.
- Using custom PHP and JavaScript code which you can use to add custom AJAX add to cart buttons in WooCommerce.
Upgrade your store with WooCommerce AJAX add to cart
Without AJAX, adding multiple products one after another to the shopping cart can be a frustrating experience for customers. Even if they stick around and complete their purchase, full-page reloads can cause the shopping experience to feel slow and disruptive — especially in large WooCommerce stores.
In this guide, we've explored three different methods to enable AJAX add to cart in WooCommerce — WooCommerce's built-in AJAX add to cart setting, the best WooCommerce AJAX add to cart plugins, and custom PHP and javascript AJAX code snippets.
To recap, these are the best plugins to add AJAX add to cart in WooCommerce:
- AJAX add to cart for WooCommerce - Adds AJAX add to cart buttons to individual product pages in WooCommerce.
- WooCommerce Product Table - Overhauls the default Shop and Category page layout and replaces it with an AJAX-powered, conversion-boosting quick order form.
- WooCommerce Bulk Variations - Presents variations in a user-friendly grid or price matrix on product pages, along with AJAX add to cart buttons.
- WooCommerce Fast Cart - Revamps WooCommerce's default cart and checkout flow and upgrades it with a sleek, conversion-focused popup or modal cart with a built-in checkout, complete with AJAX add to cart buttons.
Get started with these options and enable AJAX add to cart in your WooCommerce store today!