In Magento 2, you can change the order status programmatically to reflect different stages of order processing, such as processing, completed, or canceled. In this tutorial, we'll guide you through the process of changing the order status programmatically in Magento 2 with an example. Let's get started!
Create a PHP Script to Change the Order Status
Next, create a PHP script that will change the order status. You can use your preferred code editor to create a new file, e.g., change_order_status.php
, and add the following code:
<?php
use Magento\Framework\App\Bootstrap;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
require __DIR__ . '/app/bootstrap.php';
// Bootstrap Magento
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
// Load the order by increment ID
$orderIncrementId = '100000001'; // Replace with the actual order increment ID
$orderFactory = $objectManager->get(OrderFactory::class);
$order = $orderFactory->create()->loadByIncrementId($orderIncrementId);
// Update the order status
$newStatus = Order::STATE_PROCESSING; // Replace with the desired order status
$order->setStatus($newStatus);
$order->save();
echo "Order status updated successfully.";
?>
Make sure to replace '100000001'
with the actual order increment ID and 'Order::STATE_PROCESSING'
with the desired order status. You can refer to the Magento\Sales\Model\Order
class for the available order status options.