Tuesday, August 3, 2010

How to delete orders from Magento

This is a response for http://www.magentocommerce.com/boards/viewthread/197549/
Problem: How to delete (test) orders from Magento.
Possible solution:

Here is a free but 'quick and dirty' way to do it.
Create a file on the same level as index.php. Let's call it orders.php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
ini_set('display_errors', 1);
Mage::register('isSecureArea', 1);
//until here you gained access to the Magento models. The rest is custom code

$orderId = 156;//put here the id of the order you want to delete. THE ONE FROM THE DATABASE NOT THE INCREMENT_ID

$order = Mage::getModel('sales/order')->load($orderId);
$invoices = $order->getInvoiceCollection();
foreach ($invoices as $invoice){
$creditnotes = $order->getCreditmemosCollection();
foreach ($creditnotes as $creditnote){
$shipments = $order->getShipmentsCollection();
foreach ($shipments as $shipment){
Save and call it in your browser (http://my-magento.root/orders.php)
This will delete an order with the id you specify.
If you want to delete more of them just create a for (foreach) loop that will execute this code for each order you want to delete.

For example, if all your test orders are consecutive up to a number you can do this:
//let's say that the orders with ids less than 200 are test orders
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter(array(array('attribute'=>'entity_id', 'lt'=>200)));
foreach ($collection as $o){
$orderId = $o->getId();
//here goes the code above starting below $orderId = 156.

I've used it in several occasions and it worked, but please back-up before using it. I will not be responsible if something goes wrong :)