WooCommerce AJAX Cart with Quantity on Shop Page

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.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.