5

I am trying to get items quantity from the cart.

I tried using this but it responded with unexpected results:

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

That returns a number of products in the cart but not the number of items.

Example:

Product 1 - Quantity in cart (2)

Product 2 - Quantity in cart (4)

The above would give me a result of 2 but I would expect 6.

How can I achieve the above?

Magento ver. 2.2.4

3 Answers 3

7
$helper = $this->helper('\Magento\Checkout\Helper\Cart');
echo $helper->getSummaryCount();
2
  • 1
    exactly what I was looking for.
    – Greg
    Sep 5, 2018 at 13:36
  • 2
    It's not working when full page cache is enabled.
    – Vish V
    May 12, 2020 at 7:45
0

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$cart = $_objectManager->get('\Magento\Checkout\Model\Cart');

$itemsQty = $cart->getQuote()->getItemsQty();

0

You should use the checkout session. This is an example in a helper context, using dependency injection

namespace Vendor\Module\Helper;

use Magento\Checkout\Model\Session as CheckoutSession;


class Data extends AbstractHelper
{
        
        public function __construct(
               Context $context,
               CheckoutSession $checkoutSession
        ){
                 parent::__construct($context);
                 $this->checkoutSession = $checkoutSession;
        
         }
                  
         /**
          * @return float|int
          * @throws \Magento\Framework\Exception\LocalizedException
          * @throws \Magento\Framework\Exception\NoSuchEntityException
          */
         public function getCartItemsCount()
         {
                return $this->checkoutSession->getQuote()->getItemsSummaryQty();
         } 
}

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.