Learn how to implement a custom AJAX add-to-cart system in WooCommerce for a faster, smoother user experience without page reloads.
Introduction
By default, WooCommerce reloads the page when a product is added to the cart.
That’s bad for:
- User experience
- Conversion rates
- Performance
Modern eCommerce stores use AJAX-based add-to-cart to make everything feel instant.
In this guide, we’ll build a custom AJAX add-to-cart system from scratch.
What We’re Building
- Add product to cart via AJAX
- No page reload
- Update cart count dynamically
- Show success feedback
Step 1: Create AJAX Handler (PHP)
add_action('wp_ajax_ys_add_to_cart', 'ys_add_to_cart');
add_action('wp_ajax_nopriv_ys_add_to_cart', 'ys_add_to_cart');
function ys_add_to_cart() {
$product_id = intval($_POST['product_id']);
$quantity = intval($_POST['quantity']);
WC()->cart->add_to_cart($product_id, $quantity);
wp_send_json_success([
'message' => 'Product added to cart'
]);
}
Step 2: Add JavaScript (Frontend)
jQuery(document).ready(function($) {
$('.ys-add-to-cart').on('click', function(e) {
e.preventDefault();
let product_id = $(this).data('product');
let quantity = 1;
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'ys_add_to_cart',
product_id: product_id,
quantity: quantity
},
success: function(response) {
alert(response.data.message);
}
});
});
});
Step 3: Add Button in HTML
<button class="ys-add-to-cart" data-product="123">
Add to Cart
</button>
Step 4: Update Cart Count (Important UX)
$(document.body).trigger('wc_fragment_refresh');
This ensures cart UI updates without reload.
Real-World Use Case
This is used in:
- Fast food ordering sites
- Modern eCommerce stores
- One-page checkout systems
- Mobile-first UX
Why This Matters
This shows:
- AJAX understanding
- WooCommerce internals
- Frontend + backend integration
- Performance thinking
👉 This is what real full-stack WordPress developers do.
Final Thoughts
AJAX-based cart systems are no longer optional — they are expected.
Building this yourself shows: 👉 You’re not just using WooCommerce - you’re extending it.