AJAX Add to Cart with Quantity on WooCommerce Shop Page

Enable AJAX Add to Cart with Quantity Selectors on WooCommerce

To add AJAX functionality to the “Add to Cart” button with quantity selectors on the WooCommerce shop page, you can use JavaScript and PHP. This approach allows users to add products to their cart dynamically without refreshing the page, enhancing the shopping experience.

 

Steps to Implement AJAX Add to Cart with Quantity Selectors

 

Step 1: Create a Custom JavaScript File

First, create a new JavaScript file in your theme’s folder or a custom plugin directory. Name the file custom-ajax-add-to-cart.js and add the following code:

(function ($) {
  // Function to handle AJAX add to cart with quantity selectors
  function handleAjaxAddToCart() {
    $(document).on('submit', 'form.cart', function (e) {
      e.preventDefault();

      var $form = $(this);
      var $quantityInput = $form.find('input[name="quantity"]');
      var quantity = $quantityInput.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');
          $form.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: Enqueue the Custom JavaScript File

Next, add the JavaScript file to your theme by enqueuing it in your functions.php file:

function custom_enqueue_ajax_add_to_cart_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', 'custom_enqueue_ajax_add_to_cart_script');

 

Adjust the file path to match your setup if the JavaScript file is located in a different folder.

Step 3: Update the Shop Page Template

To ensure proper functionality, add quantity input fields within your shop template’s product loop. Here’s an example:

<?php
while (have_posts()) :
  the_post();
  $product = wc_get_product(get_the_ID());
?>

  <div <?php wc_product_class('product-item'); ?>>
    <?php
    // Display the product image, title, price, etc.
    ?>
    <form class="cart" data-product_id="<?php echo esc_attr(get_the_ID()); ?>">
      <div class="quantity">
        <input type="number" step="1" min="1" name="quantity" value="1" title="Qty" class="input-text qty text" size="4">
      </div>
      <button type="submit" class="button">Add to Cart</button>
    </form>
  </div>

<?php endwhile; ?>

Step 4: Save Changes and Test

Save your changes and test the AJAX add-to-cart functionality. Visit the WooCommerce shop page, select a quantity, and add items to your cart without a page reload.

Additional Tips

This setup assumes default WooCommerce templates. For custom themes or significant template changes, further adjustments may be necessary. Additionally, enable “AJAX add to cart buttons on archives” in WooCommerce settings under WooCommerce > Settings > Products > General.

Scroll to Top

Request A Quote