How to get the cart count via AJAX like the mini cart element?

Hello,

I have floating cart button with a badge showing the amount of items with this code:
<span class="cart-count-float"><?php echo WC()->cart->get_cart_contents_count(); ?></span>

Unfortunately it dosen’t update on add-to-cart like the badge that is available in the Woocommerce Mini Cart element that looks like this.
<span class="cart-count show" style="opacity: 1;">1</span>

Anyone can give me hint in the direction how to get it updated too? I tried to assign that classes of the Woocommerce Mini Cart element but no luck so far.

1 Like

I found a solution for anyone looking also for it:

This goes into the code element for instance above your floating cart button:

<?php
$items_count = WC()->cart->get_cart_contents_count(); 
?>
    <div class="cart-count-float"><?php echo $items_count ? $items_count : '0'; ?></div>
<?php
?>

This goes into your function.php:

//____ Cart Item Count via Ajax for floating button
add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_mini_cart_count');
function wc_refresh_mini_cart_count($fragments){
    ob_start();
    $items_count = WC()->cart->get_cart_contents_count();
    ?>
    <div class="cart-count-float"><?php echo $items_count ? $items_count : '0'; ?></div>
    <?php
        $fragments['.cart-count-float'] = ob_get_clean();
    return $fragments;
}

There maybe be better solution but it works, is simple and quick to manage.

1 Like

Thanks for sharing your solution. I wish more of these features were available natively inside Bricks Builder with dynamic data, et cetera. At the moment, the WooCommerce implementation feels a little clunky.

Has anyone figured out a way to display the count only if it’s greater than 0? Using conditions doesn’t seem to update until the page is reloaded, so I assume we’d need to hide it with JavaScript in this case.

1 Like

At the moment, the WooCommerce implementation feels a little clunky.
Yes, there is no love for the WC community is my impression over the year. Sure the basic are there, but some basics are even less functional as the WC default solutions. I stopped recommended Bricks for Shops therefor. Everything is possible with Bricks but so often it is way to time consuming for basics functionalities.

About the value “0”. No I haven’t looked for a solution. I was happy to get that topic done finally…