You are currently viewing Refresh update minicart with ajax in Woocommerce

Refresh update minicart with ajax in Woocommerce

Update minicart quantity with ajax when you remove or add new product to cart without loading the page. Use below filter hook and easily update cart quantity.

Header.php

Create HTML structure to show count in header of page like below code with id “count_cart”. Below code display count on page load. Place below code in header.php file of your child theme to show mini cart total quantity.

<div id="count_cart">
    <?php echo sprintf ( _n( '%d', '%d', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></div>

Functions.php

Now, change the mini cart quantity on adding or removing product from cart without loading the page. When cart quantity is changed below code automatically execute and update the cart quantity.

add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment',10,1 );

function woocommerce_header_add_to_cart_fragment( $fragments ) {
	global $woocommerce;
	ob_start();
	$cartcount = WC()->cart->get_cart_contents_count();
	if ($cartcount > 0){
	?>
	<div id="count_cart"><?php echo sprintf ( _n( '%d', '%d', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></div>   
   <?php     
   	$fragments['div#count_cart'] = trim(ob_get_clean());
	}else{
		$fragments['div#count_cart'] = '<span id="count_cart">0</span>';
	}
	return $fragments;
}

Leave a Reply