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
22.Jan.2024 | codedrill | Drupal
Drupal 7 to 10 migration services
Hire Codedrill for Drupal 7 to Drupal 10 migration. We also offer complete drupal development services from
11.Jan.2024 | codedrill | Apache, Hosting, Linux, MySQL, PHP
Install php 8.2, mysql, apache, phpmyadmin on ubuntu 22
All the new CMS and frameworks have started support for php 8.2. And it is quite easy to install php8.2 on