Home » WooCommerce: Ajax Add to Cart Quantity @ Shop

WooCommerce: Ajax Add to Cart Quantity @ Shop

by adminkys

As you know, you can tick the “Enable AJAX add to cart buttons on archives” checkbox in the WooCommerce settings in order to add products to cart from the Shop / Category / Tag / loop pages without refreshing the page.

This is great for certain businesses, especially those who sell in bulk and where customers know exactly what they need to buy without the need of checking the single product page.

The bad news is that the Ajax Add to Cart button only allows you to add 1 item to the cart i.e. there is no quantity input field. The other bad news is that the Ajax Add to Cart button only works for simple products, while for variable ones it will turn into a “Select options” link without the possibility of adding a variation to cart from there.

In this tutorial, we will see how to turn the WooCommerce shop into an… Ajax cart with quantity inputs. Enjoy!

With this neat snippet, the Ajax Add to Cart buttons will also get a quantity field beside them, so that customers can add as many products as they wish. This is for simple products only – variable products will show a “Select options” button instead.

PHP Snippet: Ajax Add to Cart Quantity For Simple + Variable Products @ WooCommerce Shop

/**
 * @snippet       Ajax Add Cart Quantity @ WooCommerce Shop
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 7
 * @donate $9     https://www.tutoraspire.com
 */

add_filter( 'woocommerce_loop_add_to_cart_link', 'tutoraspire_ajax_quantity_shop', 9999, 3 );

function tutoraspire_ajax_quantity_shop( $html, $product, $args ) {
if ( $product->is_purchasable() && $product->is_in_stock() && $product->supports( 'ajax_add_to_cart' ) ) {
$html = '
' . woocommerce_quantity_input( array(), $product, false ) . '
' . $html; } return $html; } add_action( 'woocommerce_after_shop_loop', 'tutoraspire_add_cart_loop_js' ); function tutoraspire_add_cart_loop_js() { wc_enqueue_js( " $(document).on('change','.quantity .qty',function(){ $(this).closest('li.product').find('a.ajax_add_to_cart').attr('data-quantity',$(this).val()); }); " ); }

You may also like