A smooth shopping experience is crucial for increasing conversions in WooCommerce.
One of the best improvements you can make is replacing page reloads with AJAX add-to-cart functionality.
In this tutorial, you will learn how to create a custom AJAX “Add to Cart” button using WooCommerce hooks.
Why AJAX Add to Cart Improves UX
When customers click “Add to Cart” without page reloads, the experience feels faster and more modern.
- Faster user experience
- No page reload interruptions
- Smoother mobile shopping
- Higher engagement and conversions
The WooCommerce Hook We Will Use
We will use:
wp_enqueue_scripts
This hook allows us to load custom JavaScript for AJAX functionality.
We will also use WooCommerce AJAX endpoints.
Step 1: Enable AJAX Add to Cart (Frontend Script)
Add this code to your theme’s functions.php file:
add_action('wp_enqueue_scripts', 'custom_ajax_add_to_cart_script');
function custom_ajax_add_to_cart_script() {
wp_enqueue_script('jquery');
wp_add_inline_script('jquery', "
jQuery(document).ready(function($) {
$('.custom-add-to-cart').on('click', function(e) {
e.preventDefault();
var product_id = $(this).data('product_id');
$.ajax({
url: wc_add_to_cart_params.ajax_url,
type: 'POST',
data: {
action: 'woocommerce_add_to_cart',
product_id: product_id,
quantity: 1
},
success: function(response) {
$(document.body).trigger('added_to_cart');
}
});
});
});
");
}
Step 2: Add Custom Button in Product Loop
Now we add a custom button using a WooCommerce hook:
woocommerce_after_shop_loop_item
Add this code:
add_action('woocommerce_after_shop_loop_item', 'custom_ajax_add_to_cart_button', 20);
function custom_ajax_add_to_cart_button() {
global $product;
if (!$product) {
return;
}
echo '
Quick Add
';
}
How It Works
- The button sends product ID via AJAX
- WooCommerce adds product to cart in background
- Cart updates without page reload
Customization Ideas
- Add quantity selector next to button
- Show mini-cart popup after add
- Animate cart icon update
- Disable button for out-of-stock products
Final Thoughts
AJAX functionality is one of the easiest ways to modernize a WooCommerce store.
It removes friction and creates a smoother shopping experience.
Small UX improvements like this often lead to big increases in conversions.
