Site icon MageComp Blog

How to get Total Order Item Quantity in Magento 2

How to get Total Order Item Quantity in Magento 2

Ecommerce is made up of several rich elements, and Magento has successfully covered all of it, and maybe that’s why it became pick for store owners. But usually, every Magento projects end at customization by giving a personalized touch to store.

Working for Magento custom development, we went through several different customization requirements and sometimes we are shocked by listening to some of the needs but Yaa, every business has its own story, own needs, and individual requirements and that’s why it’s unique.

Recently, one of the clients told us that his most of the time spent in identifying that how many quantities reside within an order. And he wanted to save his time so he can invest his valuable time in other business stuff. Maybe several times you need to know total order item quantity, so this code might help you to save your time. So, we have identified two possible way to quickly done his work using the following two methods.

Method 1: Standard Magento Method

protected $orderFactory;

public function __construct(\Magento\Sales\Model\OrderFactory $orderFactory)
{
    $this->orderFactory = $orderFactory;
}

public function execute()
{
     $orderId = 5;  //PASS YOUR ORDER ID HERE
     $order = $this->orderFactory->create()->load($orderId);
     $orderItems = $order->getAllItems();
     $total_qty = 0;
     foreach ($orderItems as $item)
     {
          $total_qty = $total_qty + $item->getQtyOrdered();
     }
     return $total_qty;
}

Method 2 : Using Object Manager (Not Recommended Method)

$order_id = 5;  //PASS YOUR ORDER ID HERE
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('Magento\Sales\Model\Order')->load($order_id);
$orderItems = $order->getAllItems();
$total_qty = 0;
foreach ($orderItems as $item)
{
   $total_qty = $total_qty + $item->getQtyOrdered();
}
 
echo $total_qty;

Note:  According to Magento Standard, Using Object Manager is not Recommended, We shared the way just for the knowledge purpose.

You can use any of two code as per the need of getting order quantity.
Lastly, hit that falling stars if the code worked for you and don’t forget to comment down below if you are looking for any help regarding this code.
Happy Coding.

Exit mobile version