1

I have a need to show products and count in header.phtml file [Magento_Theme/templates/html/header.phtml] file.

How to access those products count and data staying in header.phtml file.

What i tried :

$this->helper('Magento\Catalog\Helper\Product\Compare')->getCompareProducts();
3

Count the item collection from helper:

$this->helper('Magento\Catalog\Helper\Product\Compare')->getItemCollection()->count();

Retrieve compare list url:

$this->helper('Magento\Catalog\Helper\Product\Compare')->getListUrl();

If we want to retrieve more information about items, we can build your own. A good sample here:

vendor/magento/module-catalog/CustomerData/CompareProducts.php

 public function getSectionData()
 {
        $count = $this->helper->getItemCount();
        return [
            'count' => $count,
            'countCaption' => $count == 1 ? __('1 item') : __('%1 items', $count),
            'listUrl' => $this->helper->getListUrl(),
            'items' => $count ? $this->getItems() : [],
        ];
 }

Additionally, we also can get the compare list from the local storage: localStorage.getItem('mage-cache-storage')

JSON format:

Compare items on local storage

| improve this answer | |
  • 1
    I have used your code but that is not working on catalog, cms & product page for me in case of guest user. but for compare page , cart page and checkout page it's working. Please help me. – Balwant Singh Aug 4 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.