Magento 2 - 如何在 header.phtml 中获取购物车商品总数

Magento 2 - How to get cart items total in header.phtml

我正在使用 magento 2。我在使用

时遇到 php 错误
echo Mage::helper(‘checkout/cart’)->getCart()->getItemsCount();

如何在 magento 2 中获取购物车商品数量?

试试这个代码

<?php
  $count = $this->helper('checkout/cart')->getSummaryCount();  //get total items in cart
  $total = $this->helper('checkout/cart')->getQuote()->getGrandTotal(); //get total price
  if($count==0)
  {
    echo $this->__('<a href="/checkout/cart" class="cartgo">(0 ITEMS)</a>',$count);
  }
  if($count==1)
  {
    echo $this->__('<a href="/checkout/cart" class="cartgo">(1 ITEM)</a>',$count);
  }
  if($count>1)
  {
    echo $this->__('<a href="/checkout/cart" class="cartgo">(%s ITMES)</a>',$count);
  }
  echo $this->__('', $this->helper('core')->formatPrice($total, false));
?>
    $counter = $this->helper('\Magento\Checkout\Helper\Cart'); 
    echo $counter->getItemsCount();

Magento 2 提供了两种显示项目数量的方法。一个显示购物车中单件商品的数量,而另一个显示购物车中商品的总数。

假设购物车助手是;

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

当你这样做时:

echo $counter->getItemsCount();

它将显示购物车中单件商品的数量。

如果要显示项目总数,请使用:

echo $counter->getSummaryCount();

如果您想获得购物车中产品的总数量。

$helper = $this->helper('\Magento\Checkout\Helper\Cart');
$helper->getItemsQty(); //get total qty of the cart
$objmanager = \Magento\Framework\App\ObjectManager::getInstance();
$session =  $objmanager->get("Magento\Checkout\Model\Session");
$quote =$session->getQuote();
$qty =  $quote->getItemsSummaryQty();