Create Custom Menu in WordPress Dashboard
Complete tutorial on create custom menu in wordpress dashboard. Discover practical examples, implementation tips, and expert advice for WordPress and WooCo
Read More โAdd AJAX-powered add to cart with quantity selector on WooCommerce shop page for seamless shopping without page reloads. Implement custom JavaScript and PHP to handle dynamic cart updates, allow quantity selection in product loops, and provide instant feedback when products are added. Improves user experience and reduces cart abandonment with modern shopping functionality.
Want to allow users to select quantity and add products to their WooCommerce cart without refreshing the page? Use AJAX and a little PHP to make it seamless.
How to Add AJAX Cart with Quantity in WooCommerce
Step 1: Create a JS File
Start by making a JavaScript file named custom-ajax-add-to-cart.js inside your theme or plugin folder. Paste this code inside:
(function ($) {
function handleAjaxAddToCart() {
$(document).on('submit', 'form.cart', function (e) {
e.preventDefault();
var $form = $(this);
var quantity = $form.find('input[name="quantity"]').val();
var data = $form.serialize();
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: data + '&add-to-cart=' + $form.data('product_id'),
beforeSend: function () {
$form.removeClass('success added-to-cart').addClass('loading');
},
complete: function () {
$form.removeClass('loading');
},
success: function (response) {
if (response && response.fragments) {
$.each(response.fragments, function (key, value) {
$(key).replaceWith(value);
});
}
},
});
});
}
$(document).ready(function () {
handleAjaxAddToCart();
});
})(jQuery);
Step 2: Load the Script in functions.php
Add this function in your functions.php:
function load_custom_ajax_script() {
if (is_shop()) {
wp_enqueue_script('custom-ajax-add-to-cart', get_stylesheet_directory_uri() . '/custom-ajax-add-to-cart.js', array('jquery'), '1.0', true);
}
}
add_action('wp_enqueue_scripts', 'load_custom_ajax_script');
Step 3: Add Quantity in Loop Template
Insert quantity input fields in your product loop:
<?php while (have_posts()) : the_post(); $product = wc_get_product(get_the_ID()); ?>
<div <?php wc_product_class('product-item'); ?>>
<form class="cart" data-product_id="<?php echo esc_attr(get_the_ID()); ?>">
<div class="quantity">
<input type="number" name="quantity" value="1" class="input-text qty text" min="1" step="1">
</div>
<button type="submit" class="button">Add to Cart</button>
</form>
</div>
<?php endwhile; ?>
Step 4: Save and Verify
Test your new setup on the WooCommerce shop page. Items should add to the cart dynamically.
Tips
Ensure the AJAX setting is enabled under WooCommerce → Settings → Products → General. Template changes may require adjustments. 
Search our archives or reach out to our team for solutions and expert advice.