Magento 2 programmatically add custom order status

Today we talk about how in Magento 2 programmatically add custom order status. This tutorial includes set custom order status and also set the default magento order status too. You have to inject Magento\Sales\Model\Order to set order status. So let start with our example.

Dependency Injection

protected $orderFactory;
public function __construct(
           
        \Magento\Sales\Model\OrderFactory $orderFactory,

    ) {


        $this->orderFactory = $orderFactory;

    }

public function customOrderStatus(){
        $orderId = 3;
        $order = $this->orderFactory->create()->load($orderId);
        $state = $order->getState();
        $status = 'custom_cancel';
        $comment = 'This is test comment';
        $isNotified = false;
        $order->setState($state);
        $order->setStatus($status);
        $order->addStatusToHistory($order->getStatus(), $comment);
        $order->save();
}

Object Manager

        $orderId = 3;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
        $state = $order->getState();
        $status = 'custom_cancel';
        $comment = '';
        $isNotified = false;
        $order->setState($state);
        $order->setStatus($status);
        $order->addStatusToHistory($order->getStatus(), $comment);
        $order->save();

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply