Pawan Kumawat

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

Related Blogs

Create WooCommerce Orders Programmatically

To create WooCommerce orders programmatically in WordPress, you can use the `wc_create_order()` function provided by WooCommerce. This function allows you to create orders and add products to them. Make sure you have WooCommerce installed and activated in your WordPress environment. Here’s a step-by-step guide:

Add Custom Price on Bulk Purchase in Woocommerce Using ACF

To achieve this functionality, you’ll need to create a custom ACF repeater field for quantity and price in the product admin panel and then display all the prices on the product single page. Additionally, you’ll have to calculate the price according to the selected quantity when a product is added to the cart using WordPress hooks.

How to Remove Product Tabs on Product Page

To remove product tabs on the WooCommerce product page, you can use the `woocommerce_product_tabs` filter. This filter allows you to modify or remove the default product tabs provided by WooCommerce. By removing the tabs you don’t want, you can customize the product page layout to suit your needs.