0

Client wants to display a conditional message on the category list.phtml page depending on whether or not the cart has ANYTHING in it

I've found a lot of posts about creating a custom module to be able to assess cart items etc. but surely there must just be a simple way of identifying whether the cart contains anything or not without the need for a whole module to do so.

I don't care if we're counting items, reporting totals, assessing whether a cart exists or however it's done I just need a 'cart_empty' true or false variable

Any ideas?

UPDATED: reading a little more on this, I think the issue may be because we have caching in place on the product list page for performance reasons

This being the case do I need to access the cart using AJAX in some way?

2 Answers 2

1

You should use minicart knockout, otherwise cache will be a problem. Just name the scope different like 'cart_check'. In your list.phtml

<div data-bind="scope: 'cart_check'">
<!-- ko ifnot: getCartParam('summary_count') -->
  <div class="block-content no-display"
       data-bind="css: {'no-display': getCartParam('summary_count')}">
        <span>NO ITEMS IN CART</span>
  </div>
<!-- /ko -->
</div>

and

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "cart_check": {
                    "component": "Magento_Checkout/js/view/minicart"
                }
            }
        }
    }
}
</script>
1
  • Works perfectly - thanks!
    – freestate
    Apr 11, 2021 at 18:58
0

Maybe below is the simple way in any list.phtml file.

$cartHelper = $this->helper(Magento\Checkout\Helper\Cart::class);
if ($cartHelper->getItemsCount() === 0) {
   // write your code       
}
2
  • Thanks but this isn't working for me - I don't think it's working because getItemsCount always shows as 0
    – freestate
    Apr 11, 2021 at 14:38
  • check all function from "vendor\magento\module-checkout\Helper\Cart.php" and get current quote or cart object, or checkout session and you can get count or number of items from current quote object. Apr 11, 2021 at 18:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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