0

I am having an issue,How to display the cart number on each page?

$helper = $this->helper('\Magento\Checkout\Helper\Cart');
echo $helper->getItemsCount();

or

$helper = $this->helper('\Magento\Checkout\Helper\Cart::class');
echo $helper->getSummaryCount();

Can only be displayed on the shopping cart page, and still displays 0 on other pages

Bob
  • 15
  • 8

2 Answers2

0

try following code.

<script type="text/javascript">
    require([
        'Magento_Customer/js/customer-data'
    ], function (customerData) {
        'use strict';
    customerData.get('cart').subscribe(function (cartInfo) {
        //HERE YOU WANT TO DO THE CODE WHERE YOU WANT TO SHOW THIS
        console.log(cartInfo['summary_count']);
    }, this);
});

</script>

Dhiren Vasoya
  • 9,484
  • 12
  • 33
  • 59
0

Try This Code

app/code/VendoreName/ModuleName/view/frontend/layout

default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="main.content">
            <block class="Magento\Framework\View\Element\Template" name="custom-block-name" template="VendoreName_ModuleName::showcartnumber.phtml" before="-"/>
        </referenceContainer>
    </body>
</page>

app/code/VendoreName/ModuleName/view/frontend/templates

showcartnumber.phtml

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$cart_id=$cart->getQuote()->getId();
if ($cart_id) {
    ?>
        <h1>Cart Number : <?php echo $cart_id; ?> </h1>
    <?php
}
?>
Msquare
  • 9,063
  • 7
  • 25
  • 63