Magento - How to get cart items total in header.phtml

Magento - How to get cart items total in header.phtml

August 28, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento - How to get cart items total in header.phtml

Magento - How to Correctly Retrieve Cart Items Total in header.phtml

Hello developers! Today, I’m going to walk you through how to properly retrieve and display the total number of items currently in your customer’s cart within the header.phtml file of a Magento eCommerce store.

The Problem with the Current Code

The provided code is not working because it’s missing one crucial piece: the correct usage of the template helper function. Let me explain what needs to change.

<?php $cartQty = $this->getSummaryCount(); ?>

The issue lies in how you’re trying to call the getSummaryCount() method. In Magento templates, the $this variable is an instance of a block type. To call its methods, you need to use the correct syntax.

The Correct Solution

Here’s the corrected code:

<?php $cartQty = $this->helper('checkout')->getCart()->getItemsCount(); ?>

Let me break this down for you:

  • $this->helper('checkout'): This line is calling the checkout helper. Magento has a number of built-in helpers, and in this case, we need the one associated with the checkout process.

  • $this->helper('checkout')->getCart(): The getCart() method then retrieves the current shopping cart instance from the session.

  • $this->helper('checkout')->getCart()->getItemsCount(): Finally, the getItemsCount() method returns the total number of items currently in the cart.

Displaying the Cart Item Count

Now, let’s modify the provided code to actually display this information to your customers:

<?php $cartQty = $this->helper('checkout')->getCart()->getItemsCount(); ?>
<?php if ($cartQty > 0): ?>

    <?php echo $this->__('<a class="cartgo" href="%s">(%s ITEMS)</a>', $this->getUrl('checkout/cart'), $cartQty) ?>

<?php endif; ?>

Here, we first check if there are any items in the cart. If so, we use the __() function to dynamically generate a link to the shopping cart page with the item count appended.

Conclusion

In this post, I’ve shown you how to correctly retrieve and display the total number of items currently in your customer’s cart within header.phtml. Remember, it’s crucial to understand how Magento’s template system and helpers work together to retrieve data from the session.

This is a common use case that many developers face when customizing their Magento storefront. I hope this explanation helps you not only solve this specific issue but also provides insight into working with Magento templates more effectively.

If you’re looking for deeper insights, be sure to check out our comprehensive guides on Magento Development at LaravelCompany.com. We cover everything from basic setup to advanced customizations and optimization techniques.

Happy coding!

Checkout Themes Customers Pricing

Our network