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?