Home/Wordpress/Ajax based header cart items count in Woocommerce

Ajax based header cart items count in Woocommerce

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.

Leave a Reply

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

Recent Posts

2