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.

Related Blogs

How To Add Menu In WordPress Admin Panel

How to add menu in WordPress admin panel – In this post we see how we can add custom menu to admin sidebar. Sometimes when we on WordPress and we need to show some features or any information in admin page then we can use this code snippet to create the same.

Cron Job WordPress (WP-Cron)

What Is Wordpress Cron Job? Wordpress Cron Job is how WordPress handles scheduling time-based tasks in WordPress.“Cron” Means the cron time-based task scheduling system which is available on UNIX systems.

How To Create A Custom Product Tab On Product Page WooCommerce

To create a custom product tab on a WooCommerce product page, you’ll need to use some custom code. WooCommerce provides hooks and filters that allow you to extend and modify its functionality. Below are the steps to create a custom product tab in WooCommerce:

Request A Quote

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.