1

I am creating a custom header that displays the cart count with a little shopping cart icon. This icon is not the one automatically generated by Woocommerce, as the client is using a theme that removes that.

By default, a zero is displayed but replaced with the cart count assuming there are items within the cart.

What I built seems to be working just fine when logged in. When not logged in, no cart count is retrieved and the zero remains.

The function I've written is like so:

<?php echo WC()->cart->get_cart_contents_count(); ?>

I've also tried:

<?php

global $woocommerce;

echo $woocommerce->cart->get_cart_contents_count();

?>

The menu item in the header is structured like so:

<li id="menu-item-8575" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-8575">
    <a href="/cart/">
        <span class="qode_icon_font_elegant icon_cart qode_icon_element"></span>
        <span class="cart-count">0</span> Items
    </a>
</li>

Here is the full code that gets the cart count with PHP and then uses JS to replace the cart number in the "cart-count" span element.

<?php $cartCount = WC()->cart->get_cart_contents_count(); ?>

<script>
jQuery(document).ready(function( $ ) {
    var cartCount = '<?php echo $cartCount ?>';
    $('.cart-count').html(cartCount);
});
</script>

When logged in, the whole thing works as expected. When not logged in, the $cartCount variable doesn't seem to grab anything. Is there a missing piece to getting the cart count that I haven't accounted for?

Austin Verburg
  • 75
  • 2
  • 11
  • See [Ajaxify header cart items count in Woocommerce](https://stackoverflow.com/questions/51123903/ajaxify-header-cart-items-count-in-woocommerce/51126271?r=SearchResults&s=1|52.5216#51126271) – LoicTheAztec Aug 19 '19 at 01:37
  • Not quite doing it. I've added the function, updated it to target my .cart-count span tag, and put the jquery in to trigger the refresh, and am now not getting any sort of update at all even when logged in. – Austin Verburg Aug 19 '19 at 21:39
  • 1
    Interesting, I tried removing all items from my cart and that triggered the fix. Thank you!! – Austin Verburg Aug 19 '19 at 21:47

0 Answers0