I'm using the following code to cancel programmatically some orders in my magento website:

foreach($orderCollection as $order):
    $order = Mage::getModel('sales/order')->load($order->getId());

    $order->setData('state', "canceled");
    $order->addStatusHistoryComment('Order was automatically canceled');


The problem is that the order's product quantities, that were decreased when order was placed, are not increased back their previous state, after order is canceled.

Can you help me fix that?

*Note: Product quantities are restored if I cancel order through magento administration. But it's not working when canceling orders programmatically.

  • please try my solution as below Commented May 18, 2018 at 11:05

3 Answers 3


Why you use external cancel functionality to load model each time, Magento Provide cancle() function.

Try This code to cancel order:

if(!$order->canCancel()) {
    throw new Exception('Order cannot be canceled anymore.');

I give you such idea to use cancel() like:-

$orderModel = Mage::getModel('sales/order');
if(!$orderModel->canCancel()) {
$orderModel->setState(Mage_Sales_Model_Order::STATE_CANCELED, true);

System->Configuration-> Catalog ->inventory->stock options->Set Items' Status to be In Stock When Order is Cancelled change this value to "No".

You can also stop to decrease the stock quantity on order placed: System->Configuration-> catalog -> inventory->stock options->Decrease Stock When Order is Placed

  • I tried using your code but still the product qty is not restored.
    – zekia
    Commented May 18, 2018 at 8:15
  • hey have you check configuration, i just edit my answer @zekia
    – Divyesh
    Commented May 18, 2018 at 9:49
  • I need to keep increasing/decreasing stock quantities. This is not a solution for my ehop. As I mentioned in my question, product quantities are restored if I cancel order through magento administration. But it's not working when canceling orders programmatically.
    – zekia
    Commented May 18, 2018 at 10:17

Please Try below code for cancel order and manage inventory of Products ordered. Its working fine for me :

require_once 'app/Mage.php';
$order = Mage::getModel('sales/order')->loadByIncrementID('100000015'); // Your order increment id
  • I tested the code and it's not canceling the order. Any ideas?
    – zekia
    Commented May 18, 2018 at 12:25
  • @zekia , code updated. Commented May 18, 2018 at 12:32
  • I'm running this through an .sh file, in case that matters at all
    – zekia
    Commented May 18, 2018 at 13:25
  • Can you try this script for manually in browser? Commented May 18, 2018 at 13:25
  • I'll try this, but my initial script loads and cancels order normally. I think that the $order->cancel()->save(); is not working in your code. I'll let you know in a while
    – zekia
    Commented May 18, 2018 at 13:29

Below code worked in Magento 2

Automatically cancel pending payment orders older than 1 day using cron

Create a custom module with required files


<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="order_cancel_orders" instance="Custom\Module\Cron\OrderCancelOrders" method="execute">
            <schedule>*/5 * * * *</schedule>



namespace Custom\Module\Cron;

use Exception;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;
use Magento\Sales\Model\Order;

class OrderCancelOrders

    protected $productRepository;
    protected $dateTime;
    protected $logger;
    protected $date;
    protected $orderRepository;
    protected $searchCriteriaBuilder;
    protected $orderManagement;

    public function __construct(
        ProductRepositoryInterface $productRepository,
        DateTime $dateTime,
        TimezoneInterface $date,
        LoggerInterface $logger,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        OrderManagementInterface $orderManagement
        $this->productRepository = $productRepository;
        $this->dateTime = $dateTime;
        $this->logger = $logger;
        $this->date = $date;
        $this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->orderManagement = $orderManagement;

    public function execute()
        $this->logger->info('Orders Cancel cron job running');
        $date = (new \DateTime())->modify('-1 day');
        $searchCriteria = $this->searchCriteriaBuilder
        try {
            $ordersData = $this->orderRepository->getList($searchCriteria);
            foreach ($ordersData->getItems() as $orders) {
                if ($orders->getId()) {
                    $this->logger->info("OrderID# {$orders->getId()} OrderIncrementID# {$orders->getIncrementId()} successfully order canceled and reverted stock.");
        } catch (\Exception $e) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.