Magento – Delete all cancelled magento orders

There are many plug-ins are available that would add option to delete order in grid actions drop-down. But I had some requirement toset a cron job that would delete all canceled orders. We know well how to create cron job, if not this post will help you to create cron job in magento.

You can add bellow code to your model funtion that would be run by the cron job,

$collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('*')
            ->setPageSize(1000)
            ->addFieldToFilter('status', 'canceled')
	    ->load();

foreach ($collection as $col) {
  Mage::log($col->getIncrementId() . ' order deleted ');
    try {
         $col->delete();
    } catch (Exception $e) {
        throw $e;
    }
}
Advertisements

4 thoughts on “Magento – Delete all cancelled magento orders

    • Hello Tobias,

      You can edit below code to detele orders between particular time,

      $time = time();
      $to = date('Y-m-d H:i:s', $time);
      $lastTime = $time - 172800; // 60*60*48
      $from = date('Y-m-d H:i:s', $lastTime);

      $collection = Mage::getResourceModel('sales/order_collection')
      ->addAttributeToSelect('*')
      ->setPageSize(1000)
      ->addFieldToFilter('status', 'canceled')
      ->addAttributeToFilter('created_at', array('from' => $from, 'to' => $to))
      ->load();

      Happy Coding!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s