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 | |

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.