How to Update cart without page reload in WooCommerce?

How would you feel if the page reloads every time you add something new to your cart? Annoying? When a user is purchasing products from your WooCommerce website and the page does not dynamically updates the cart, the whole buying process becomes slower. It’s also boring as they have to wait for a while to get it accurate.

If you want to give your site visitors a cheerful buying experience, We give you a great solution, which will update the cart dynamically whenever products are added to the cart via AJAX.

This would be real-time update and will turn the whole activity into a seamless process. Using this solution, you will save their time and, in return, will retain more users on your site.

We share a code below that will help you achieve this feature. Just place this code into the functions.php and your website will start updating the cart without refreshing the page, which will, eventually, avoid the time delay that results from the page reloading.

[codesyntax lang=”php”]

<span class="cart-contents"><a href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a></span>

// (place the following in functions.php)
add_filter('add_to_cart_fragments', 'woocommerceframework_header_add_to_cart_fragment');

function woocommerceframework_header_add_to_cart_fragment( $fragments ) {
	global $woocommerce;
	
	ob_start();
	
	?>
	<span class="cart-contents"><a href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a></span>
	<?php
	
	$fragments['span.cart-contents'] = ob_get_clean();
	
	return $fragments;
	
}

[/codesyntax]

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *