How to make the cart automatically update when the quantity of products is changed – Learn WordPress from a to z

Tutorials 0 lượt xem

Have you ever thought, it would be better if the cart automatically updated when the quantity of products changed?

automatic cart update

When you change the product quantity, the cart will be updated immediately. This is very easy to do with just a few lines of code, let’s get started!

Remove the Update Cart button

Since the cart will be automatically updated, the Update Cart button will now become redundant. I will use CSS to remove this button.

.woocommerce button[name="update_cart"],
.woocommerce input[name="update_cart"] {
	display: none;
}

Please add the above code to your theme’s style file.

If you’re worried this feature might not work properly, skip this step. Come with me to the next step!

Update cart when product quantity changes

In this step, I will have to catch the event when the number of products changes, and from there the cart will be updated. I will use a short jQuery here.

jQuery( function( $ ) {
	$('.woocommerce').on('change', 'input.qty', function(){
		$("[name='update_cart']").trigger("click");
	});
} );

The code above is very basic but not perfect. Because it will send many AJAX requests! One request per quantity change! Let’s optimize it a bit.

var timeout;

jQuery( function( $ ) {
	$('.woocommerce').on('change', 'input.qty', function(){

		if ( timeout !== undefined ) {
			clearTimeout( timeout );
		}

		timeout = setTimeout(function() {
			$("[name='update_cart']").trigger("click");
		}, 1000 );

	});
} );

Now I will use the variable timeout as a delay. On the 12th line, you can adjust the delay time to suit you. The unit here is milliseconds (ms). With 1000ms corresponding to 1 second.

Please add the above code to your theme’s script file. Otherwise, you can also use hook wp_head to insert CSS code, and hook wp_footer to insert JS code.

Epilogue

I hope the above article will partly help you better in increasing the user experience for your website.

If this article was helpful and saved your time, please help me share it. Also if you are interested in similar topics, read other WooCommerce Tips articles and follow Fanpage so you don’t miss new posts from me.

Bài viết liên quan