2

I need to get the total weight of products which are added to cart in magento2.

How can We achieve this?

3
  • have you tried to do like $product->getWeight() this ? Commented Feb 16, 2017 at 11:49
  • 1
    $product->getWeight() is used for particular product. but i want weight of all product available in cart. Commented Feb 16, 2017 at 13:46
  • For magento 1.9.2.3 how can i use, i mean total weight of cart
    – zus
    Commented Mar 12, 2018 at 11:06

1 Answer 1

5

I found the solution:

We get total weight of products of cart in Magento 2 by \Magento\Checkout\Model\Cart class

With objectManager

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

$weight = 0;
foreach($items as $item) {
    $weight += ($item->getWeight() * $item->getQty()) ;        
}

echo $weight;

With Factory Method

protected $_cart;

public function __construct(
    ...
    \Magento\Checkout\Model\Cart $cartModel,
    ...
) {
    ...
    $this->_cart = $cartModel;
    ...
}

public function getTotalWeight()
{
    $items = $this->_cart->getQuote()->getAllItems();

    $weight = 0;
    foreach($items as $item) {
        $weight += ($item->getWeight() * $item->getQty()) ;        
    }

    return $weight;
}
5
  • 1
    Which files would I put this code in?
    – samreg
    Commented Sep 10, 2017 at 20:46
  • How can i find customer add-to-cart overall weight mage 1.9 @ magento.stackexchange.com/q/221525/57334
    – zus
    Commented Apr 9, 2018 at 5:21
  • Where to put this code ? @samreg Commented Jul 30, 2018 at 8:52
  • it shouldn't be made by custom totals? Commented Apr 25, 2019 at 9:16
  • @WojciechKa Can you explain in details ? Commented Apr 29, 2019 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.