1

I want to delete orders and associated data from my store programmatically. Share any idea, How can we do that?

2

You can use Magento\Sales\Model\OrderFactory.

/** @var \Magento\Sales\Model\OrderFactory $order **/

protected $order;

public function __construct(
    \Magento\Sales\Model\OrderFactory $order,
    ......
) {
    $this->order = $order->create();

}

for getting order you can use.

$order = $this->order->loadByIncrementId('XXXXXXXXX');
// delete all invoices related to order
$invoices = $order->getInvoiceCollection();    
foreach($invoices as $invoice){
    $invoice->delete();
}

// delete all shipments related to order
$shipments = $order->getShipmentsCollection();
foreach($shipments as $shipment){
    $shipment->delete();
}


//delete all creditmemos related to order
$creditmemos = $order->getCreditmemosCollection();
foreach($creditmemos as $creditmemo){
    $creditmemo->delete();
}

// finally delete order
$order->delete();
1
<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$registry = $objectManager->get('Magento\Framework\Registry');

$id = 10; // your order_id 
$order = $objectManager->create('Magento\Sales\Model\Order')->load($id);

// $incrementId = 'xxxxxxxxx';
// $order = $objectManager->create('Magento\Sales\Model\Order')->loadByIncrementId($incrementId);

$registry->register('isSecureArea','true');
$order->delete();
$registry->unregister('isSecureArea'); 

I have shared with Object Manager but always use use dependency injection.

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