Ajax based header cart items count in Woocommerce
23.Feb.2021
If you are struggling to display cart count in the small header widget, then here is the classic way of doing it. Woocommerce has an inbuilt feature to refresh the fragments.

1) The HTML to be refreshed: So first in your theme’s header.php
file you need to embed the cart count in a specific HTML tag with a defined unique ID (or a class), for example, something like:
<div id="mini-cart-count"></div>
2) The code: Put in functions.php
add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_count');
function wc_refresh_mini_cart_count($fragments){
ob_start();
?>
<div id="mini-cart-count">
<?php echo WC()->cart->get_cart_contents_count(); ?>
</div>
<?php
$fragments['#mini-cart-count'] = ob_get_clean();
return $fragments;
}
This will automatically refresh the count as soon as an item is added to the cart. If you want to forcefully refresh the count then :
$(document.body).trigger('wc_fragment_refresh');
Leave a Reply
We'll try to resolve your queries asap.
Recent Posts
24.Mar.2025 | codedrill | Apache, Cpanel, Hosting, Wordpress
Fixing Gutenberg White Screen on GoDaddy
If you’re using WordPress with the Gutenberg editor on GoDaddy hosting and encountering a white screen or
7.Nov.2024 | codedrill | Uncategorized
Fun and Interactive Number Game for Kids: Learning ‘Before, After, and Between’ Numbers from 1 to 40
Looking for a fun, interactive way to help young children learn basic number concepts? This simple web-based