Magento: Delete Orders Programmatically

Here is a quick code to delete orders programmatically in Magento. In Magento, there isn’t the facility to delete orders from admin grid. You need to write custom code to delete orders in Magento.

Here is the full code to do so. This code can be saved in a new file in your Magento root folder and then you can run it in browser.

In this code, I have selected orders created within a certain date range. And then deleted those selected orders individually.


/**
 * Delete Orders
 *
 */
require 'app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);

$dateFrom = '01/01/2015';
$dateTo = '30/01/2015';

$fromDate = Mage::app()->getLocale()->date($dateFrom)->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);
$toDate = Mage::app()->getLocale()->date($dateTo)->toString(Varien_Date::DATETIME_INTERNAL_FORMAT);

$orderCollection = Mage::getModel('sales/order')->getCollection()
			->addAttributeToFilter('created_at', array('date' => true, 'from' => $fromDate))
			->addAttributeToFilter('created_at', array('date' => true, 'to' => $toDate));

# echo $orderCollection->printLogQuery(true);

if ($orderCollection->count()) {
	foreach ($orderCollection as $order) {
		try {			
			Mage::getModel('sales/order')->loadByIncrementId($order->getIncrementId())->delete();
			echo "Order #" . $id . " is removed" . PHP_EOL;
			Mage::log("Order #" . $id . " is removed", null, "order-delete.log");
		} catch (Exception $e) {
			echo "Order #" . $id . " could not be remvoved: " . $e->getMessage() . PHP_EOL;
			Mage::log("Order #" . $id . " could not be remvoved: " . $e->getMessage(), null, "order-delete.log");
		}
	}
	echo "<br>";
	echo "Completed.";
	Mage::log("Completed.", null, "order-delete.log");
}

Hope this helps.
Thanks.