Custom Cart Item Count

Add below code where you want to show cart count.

<span class="count">
	<?php global $woocommerce; echo $woocommerce->cart->cart_contents_count; ?>
</span>

 

Add the below code in function.php file.

add_filter( 'woocommerce_add_to_cart_fragments', 'cart_count_fragments', 10, 1 );
function cart_count_fragments( $fragments ) {
	$val = WC()->cart->get_cart_contents_count();
	if($val == 0){
		$fragments['span.count'] = '<span class="count" style="opacity:0"></span>';
	}else{
		$fragments['span.count'] = '<span class="count" style="opacity:1">' . WC()->cart->get_cart_contents_count() . '</span>';
	}
    return $fragments;
}

Leave a comment