Over the years, online shopping has gained fame and due to that nowadays if someone wants to buy a product, instead of walking into the store people has started ordering products online with just a few clicks. To run a successful online E-commerce business there are several CMS available to handle sales and product easily by reducing efforts of store owners. Once the order is placed it passes through various order states and statuses and shipping is one of them. Creating a shipment for an order doesn’t take a long but when there is a large number of orders it becomes a time-consuming task for store owners.
Recently we need to generate shipment for multiple orders and to save time and efforts we created a script to generate shipment programmatically in Magento 2 and it worked because it is useful to everyone we decided to share on our MageComp blog.
All you need to do is simply upload this script on the root folder of your server and hit the URL of script followed by the filename.
Create a file in your Magento root directory at the below path
magento_root_directory\shipmentcreate.php
<?php
use \Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$orderInterface = $objectManager->get('\Magento\Sales\Api\Data\OrderInterface');
//Use this if you have orderId
//$orderId = "100"; //Order Id
//$order = $orderInterface->load($orderId);
$incrementId = "000000165"; //Increment Id
$order = $objectManager->create('Magento\Sales\Model\Order')->loadByAttribute('increment_id', $incrementId);
if ($order->canShip()) {
// Initialize the order shipment object
$convertOrder = $objectManager->create('Magento\Sales\Model\Convert\Order');
$shipment = $convertOrder->toShipment($order);
// Loop through order items
foreach ($order->getAllItems() AS $orderItem) {
// Check if order item has qty to ship or is virtual
if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
continue;
}
$qtyShipped = $orderItem->getQtyToShip();
// Create shipment item with qty
$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();
} catch (\Exception $e) {
echo "Shipment Not Created". $e->getMessage(); exit;
}
echo "Shipment Succesfully Generated for order: #".$incrementId;
} else {
echo "Shipment Not Created Because It's already created or something went wrong";
}
Happy Coding!
