
In Magento 2, creating a shipment programmatically is the convenient way to add the new shipment as you need. If we need to programmatically create shipment for an order then you can create by following way.
Use the following code to create shipment programmatically for an order in Magento 2:
<?php // Loading the Order $order = $this->_objectManager->create('Magento\Sales\Model\Order') ->loadByAttribute('increment_id', '000000001'); //OR $order = $this->_objectManager->create('Magento\Sales\Model\Order') ->load('1'); // Check if order has already shipping or can be shipped if (! $order->canShip()) { throw new \Magento\Framework\Exception\LocalizedException( __('You cant create the Shipment.') ); } // Initializzing Object for the order shipment $convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order'); $shipment = $convertOrder->toShipment($order); // Looping the Order Items foreach ($order->getAllItems() AS $orderItem) { // Check if the order item has Quantity to ship or is virtual if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) { continue; } $qtyShipped = $orderItem->getQtyToShip(); // Create Shipment Item with Quantity $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped); // Add Shipment Item to Shipment $shipment->addItem($shipmentItem); } // Register Shipment $shipment->register(); $shipment->getOrder()->setIsInProcess(true); try { // Save created Shipment and Order $shipment->save(); $shipment->getOrder()->save(); // Send Email $this->_objectManager->create('Magento\Shipping\Model\ShipmentNotifier') ->notify($shipment); $shipment->save(); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException( __($e->getMessage()) ); }
Let me know if you have any question or faced any issue while following this method for creating Shipment Programmatically in Magento 2.