The method to create shipment programmatically in Magento 2 is a convenient way to add more shipping methods to the Magento 2 store.
Online shopping is gaining popularity and merchants require to fulfill the order with the best facility in order to stand the competition. Shipping is one of them.
Shipping is an important factor in conversion, and these findings from Statista prove the same:
- Shipping terms are an important factor when ordering online – low acceptance rate for high shipping costs
- Even with free shipping, 80% of shoppers expect delivery within seven days at the latest
- Shipment tracking and delivery notifications are the most-used services offered by shipping providers and for that you need to add tracking number to current order shipment in Magento 2.
- Low use of fast shipping and scheduled delivery options; young shoppers use them the most
- Younger online shoppers are more likely to use express shipping options to avoid long delivery times
- Online shoppers are open to new delivery methods (e.g. via robots and drones)
Creating shipment in Magento 2 can be complex, but not with the programmatic method, which will save your time!
Use the following code to create shipment programmatically for order in Magento 2:
<?php // Loading the Order $order = $this->_objectManager->create('MagentoSalesModelOrder') ->loadByAttribute('increment_id', '000000001'); //OR $order = $this->_objectManager->create('MagentoSalesModelOrder') ->load('1'); // Check if order has already shipping or can be shipped if (!$order->canShip()) { throw new MagentoFrameworkExceptionLocalizedException( __('You cant create the Shipment.')); } // Initializzing Object for the order shipment $convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder'); $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('MagentoShippingModelShipmentNotifier') ->notify($shipment); } catch (Exception $e) { throw new MagentoFrameworkExceptionLocalizedException( __($e->getMessage()) ); }