user6952436 user6952436 - 1 month ago 11
HTML Question

Showing the number of items in WooCommerce mini cart

I am creating a cart link for my mobile header. I just want to show number of cart items after the cart icon. No text, only a number.

How can I do it?

My code is something like this:

<div class="mobile-cart">
<a href="mywebsite.com/cart">
<img src="cart.png">
Here should be the code for no. of items
</a>
</div>


Thanks.

Answer

You just need to use the method get_cart_contents_count() from WC_cart class, this way:

<div class="mobile-cart">
    <a href="mywebsite.com/cart">
         <img src="cart.png">
         <span><?php echo WC()->cart->get_cart_contents_count( ); ?></span>
     </a>
</div>

Reference: WC_Cart class - get_cart_contents_count() method