Magento2 – How to Get Cart Item Quantity on Front End

cartmagento2quantity

I am currently using this code and it is working fine,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$totalQuantity = $cart->getQuote()->getItemsQty();    

but it is not working on few category pages as well as Home page in my theme.
Please help.

Best Answer

use below code

public function __construct(
    \Magento\Customer\Model\Session $currentCustomer
) { 
    $this->checkoutSession = $checkoutSession;   
 }


 $cartQuote=$this->checkoutSession->getQuote();  
 $items=$cartQuote->getAllItems();

Or

  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $checkoutSession = $objectManager->get('\Magento\Customer\Model\Session');
  $cartQuote=$checkoutSession->getQuote();  
  $items=$cartQuote->getAllItems();