/**
 * @var \Magento\Checkout\Model\Session
 */
 protected $_checkoutSession;
 
 public function __construct(
   \Magento\Checkout\Model\Session $checkoutSession,
   \Magento\Framework\App\Action\Context $context,
    array $data
 )
 {
   parent::__construct($context, $data);
   $this->_checkoutSession = $checkoutSession;
 }
 
 public function execute()
 {
     echo $this->countItemsInCart(); 
 }
 
 public function countItemsInCart()
 {
     $cartItems = $this->_checkoutSession->getQuote()->getAllVisibleItems();
     $cartItemsCount = count($cartItems);
     return $cartItemsCount;
 }
Advertisements