Ajax Add to Cart Quantity on Shop WooCommerce

To enable AJAX add to cart with quantity selectors on the WooCommerce shop page, you’ll need to use JavaScript to handle the AJAX request and update the cart quantity dynamically. Below are the steps to achieve this:

Step 1: Create a Custom JavaScript File Create a new JavaScript file in your theme’s folder or a custom plugin. Name it something like 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, you need to enqueue the custom JavaScript file on the WooCommerce shop page. Add the following code to your theme’s functions.php file or a custom plugin:

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');

Make sure to adjust the path to the custom-ajax-add-to-cart.js file if it’s located in a different folder.

Step 3: Update Shop Page Template If your shop page is displaying product archives differently from the default WooCommerce templates, you may need to update the template file to include the necessary form elements and quantity selectors. The form element must have the class="cart" and a data-product_id attribute with the product ID as its value.

Here’s an example of how a product loop item might look:

<?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 the changes to your theme’s functions.php file or custom plugin and ensure the custom-ajax-add-to-cart.js file is properly enqueued. Now, when you visit the WooCommerce shop page, you should see the quantity selectors next to the “Add to Cart” buttons. When a customer selects a quantity and clicks the “Add to Cart” button, the product will be added to the cart using AJAX without the need for a page refresh.

Please note that this code assumes that you are using the default WooCommerce templates and styles. If you have a custom theme or have made significant changes to the WooCommerce templates, you may need to adjust the code to fit your specific setup. Additionally, make sure that the “Enable AJAX add to cart buttons on archives” option is enabled in the WooCommerce settings under WooCommerce > Settings > Products > General.

Categories
Scroll to Top

Request A Quote