Add a Quantity Field to Ajax Add to Cart Button on Woocommerce Shop Page

Add a quantity field to Ajax add to cart button on WooCommerce shop page

Updated on 2021

For WooCommerce versions from 3.2 to 5+, Optimized jQuery code and Removed a quantity bug. Added quantity reset after add to cart.


The following custom function is hooked in woocommerce_loop_add_to_cart_link filter hook and adds a quantity input field to each product on WooCommerce archives pages and other product loops. We use here mostly the original WooCommerce code.

A bit of jQuery code is necessary to update the data-quantity attribute on the add to cart button when customer changes the quantity. Some styling might be needed, depending on your client wishes (and on your theme).

An additional section to hide the "View cart" button is located at the end.

The code:

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
// Get the necessary classes
$class = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );

// Embedding the quantity field to Ajax add to cart button
$html = sprintf( '%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
woocommerce_quantity_input( array(), $product, false ),
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button' ),
esc_html( $product->add_to_cart_text() )
);
}
return $html;
}

add_action( 'wp_footer' , 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
?>
<script type='text/javascript'>
jQuery(function($){
// Update data-quantity
$(document.body).on('click input', 'input.qty', function() {
$(this).parent().parent().find('a.ajax_add_to_cart').attr('data-quantity', $(this).val());
$(".added_to_cart").remove(); // Optional: Removing other previous "view cart" buttons
}).on('click', '.add_to_cart_button', function(){
var button = $(this);
setTimeout(function(){
button.parent().find('.quantity > input.qty').val(1); // reset quantity to 1
}, 1000); // After 1 second

});
});
</script>
<?php
}

Code goes in functions.php file of your active child theme (active theme).

Tested and works on WooCommerce version 4.1.1 and WordPress 4.5.1 on Storefront theme.


Hiding "View cart" button (when using Ajax add to cart):

1). You can add this CSS rule to the styles.css file located in your active theme:

a.added_to_cart.wc-forward {
display:none;
}

2). You can use the following hoocked function (first option is the best way):

add_action( 'wp_head' , 'hide_ajax_view_cart_button' );
function hide_ajax_view_cart_button(){
if( is_shop() || is_product_category() || is_product_tag() ): ?>
<style>
a.added_to_cart.wc-forward {
display:none;
}
</style>
<?php endif;
}

Code goes in function.php file of your active child theme (active theme).

Add a quantity radio selector field to Ajax add to cart button on WooCommerce shop page

It looks like your missing the additional jQuery required to make this work. I know you requested to make this work with a radio select but maybe to save space you want to consider a select?

The following code does just that.

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
// Get the necessary classes
$class = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );

$args = array(
'type' => 'select',
'class' => array( 'form-row-wide', 'quantity-select' ),
'options' => array(
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
'8' => '8',
'9' => '9',
'10' => '10'
),
'default' => '0'
);

// Embedding the quantity field to Ajax add to cart button
$html = sprintf( '%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
woocommerce_form_field( '', $args ),
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button' ),
esc_html( $product->add_to_cart_text() )
);
}
return $html;
}

add_action( 'wp_footer', 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
?>
<script type='text/javascript'>
jQuery(function($){
// Update data-quantity
$(document.body).on('change', '.quantity-select select', function() {
let selected_quantity = $(this).find(":selected").text();
$(this).closest('li.product').find('a.ajax_add_to_cart').attr('data-quantity', selected_quantity);
$(".added_to_cart").remove(); // Optional: Removing other previous "view cart" buttons
}).on('click', '.add_to_cart_button', function(){
var button = $(this);
setTimeout(function(){
console.log( button.siblings('.quantity-select').find('select option[value="0"]') );
button.siblings('.quantity-select').find('select').val('0'); // reset quantity to 0
}, 1000); // After 1 second
});
});
</script>
<?php
}

WooCommerce Shop page: Quantity input on add to cart button

So what I ended up doing was adding the single page add to cart action to a hook for the shop page loop as follows:

add_action('woocommerce_after_shop_loop_item',
'woocommerce_template_single_add_to_cart', 30);

Thanks.

WooCommerce Ajax add to cart quantity doesn't work

You had some invalid use of $loop->post->ID which within the loop when you've declared the_post() would be simply $post->ID

Also, $product->id should be $product->get_ID() if you're using the latest WC version.

This below is working in my test.

// Setup your custom query
$args = array( 'post_type' => 'product', 'orderby' => 'date' );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
?>
<div class="product-content-containers">
<a href="<?php echo get_permalink( $post->ID ) ?>">
<div id="mobclear" style="background-image: url(<?php echo get_the_post_thumbnail_url($post->ID);?>);" class="product-right-content">
</div>
</a>
<div id="descclear" class="product-left-content">
<h3 class="h5">
<a href="<?php echo get_permalink( $post->ID ) ?>">
<?php the_title(); ?>
</a>
</h3>
<p><?php echo apply_filters( 'woocommerce_short_description', $post->post_excerpt ) ?></p>
<div>
<p><span class="woocommerce-Price-amount amount customamount"><?php echo $product->get_price(); ?> <span class="woocommerce-Price-currencySymbol"><?php echo get_woocommerce_currency_symbol(); ?></span> pr. stk.</span></p>
<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="cart" method="post" enctype='multipart/form-data'>

<?php woocommerce_quantity_input(); ?>

<button type="submit" data-quantity="1" data-product_id="<?php echo $product->get_ID(); ?>"
class="button alt ajax_add_to_cart add_to_cart_button product_type_simple"><?php echo $label; ?></button>

</form>
</div>
</div>
</div>
<?php endwhile; wp_reset_query(); // Remember to reset ?>
<script type="text/javascript">
jQuery('input[name="quantity"]').change(function(){
var q = jQuery(this).val();
jQuery('input[name="quantity"]').parent().next().attr('data-quantity', q);
});
</script>


Related Topics



Leave a reply



Submit