2

I'm using Magento v 2.2 and I'm trying to check if the customer/visitor (doesn't matter if logged in or not) has any products in their compare list and I'm trying to do this in {theme_dir}/Magento_Catalog/templates/product/compare/link.phtml.

I tried doing this by calling the Magento\Catalog\Helper\Product\Compare helper's method hasItems(), but I'm having issues (I believe with caching).

<?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');
if ($compareHelper->hasItems()) { ?>
    //default Magento code
    <li class="item link compare" data-bind="scope: 'compareProducts'" data-role="compare-products-link">
        <a class="action compare no-display" title="<?php echo __('Compare Products') ?>"
           data-bind="attr: {'href': compareProducts().listUrl}, css: {'no-display': !compareProducts().count}"
        >
            <?php echo __('Compare Products') ?>
            (<span class="counter qty" data-bind="text: compareProducts().countCaption"></span>)
        </a>
    </li>
    <script type="text/x-magento-init">
        {"[data-role=compare-products-link]": {"Magento_Ui/js/core/app": <?php echo $block->getJsLayout();?>}}
    </script>
    //end of default Magento code
<?php } ?> 

Example situation: When customer is not logged in and adds a product to compare, the compare html doesn't show in the header.links block.

When the same customer logs in, the compare block shows on the page the customer is redirected to (which is currently the customer account page).

But when the same logged in customer switches to a different page, the compare block doesn't show again.

This seems to be a caching issue, but I'm not sure how to fix it. Any suggestions?

2
  • i check your code it's working. – Pratik Oct 26 '17 at 6:02
  • I provided more details on the issue with an edit. – Lez Oct 26 '17 at 12:36

Your Answer

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

Browse other questions tagged or ask your own question.