How to Delete a WooCommerce Order Programmatically

WooCommerce is a powerful and flexible eCommerce plugin for WordPress that allows users to set up and manage an online store with ease. However there are times when you need to delete an order programmatically. Whether you’re cleaning up test data, removing fraudulent orders or automating some aspect of your store management knowing how to delete WooCommerce orders programmatically can be very useful. In this blog post we will walk through the steps and code required to achieve this.

Understanding WooCommerce Orders

WooCommerce orders are stored as custom post types with the type shop_order in the WordPress database. Each order has associated metadata that includes customer details, order status, and other relevant information.

The Code to Delete an Order

To delete a WooCommerce order programmatically, you need to use WordPress functions to manipulate the shop_order post type. Below is the step-by-step process:

Step 1: Access Functions File

First, open the functions.php file of your active theme or create a custom plugin where you will add the code.

Step 2: Write the Function to Delete the Order

Here’s a simple function to delete an order by its ID:

/**
 * Delete a WooCommerce order programmatically.
 *
 * @param int $order_id The ID of the order to delete.
 * @return bool True on success, false on failure.
 */
function delete_woocommerce_order($order_id) {
    if ( ! $order_id ) {
        return false;
    }

    // Check if the order exists
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return false;
    }

//when you want to move the order in trash
$order->delete( false );

//When you want to delete an order permanently
//$order->delete( true );

    // Verify deletion
    return ( null === get_post( $order_id ) );
}

// Update order ID 123 with yours order ID
delete_woocommerce_order( 123 );

Explanation of the Code

  1. Function Definition: The delete_woocommerce_order function takes the order ID as a parameter.
  2. Check Order Existence: It uses wc_get_order to verify if the order exists.
  3. Delete the Order: The delete function deletes the order. The second parameter true ensures permanent deletion (bypassing the trash).
  4. Verify Deletion: The function returns true if the order is successfully deleted, otherwise false.

If you want to move all woocommerce orders to trash you can also achieve this with the below code.

<?php

global $wpdb;

// Define the custom post type for WooCommerce orders
$post_type = 'shop_order';

// SQL query to update the post status to 'trash' for all WooCommerce orders
$sql = $wpdb->prepare(
    "UPDATE {$wpdb->posts} SET post_status = 'trash' WHERE post_type = %s",
    $post_type
);

// Execute the query
$result = $wpdb->query($sql);

// Return the number of orders moved to trash
return $result;


//Now all orders are moved to trash. Go to trash and click Empty Trash button

Here is another way of deleting the orders with a specific status. remember the parameter “true” will permanently deletes the orders.

$orders = wc_get_orders( array(
	'status' => 'failed',
	'limit'  => -1,
) );

foreach ( $orders as $order ) {
	$order->delete( true );
}

// Display a message indicating how many orders were deleted
echo 'Total failed orders deleted: ' . count( $orders );

Best Practices

Safety Checks

  • Always verify that the order ID exists before attempting to delete it.
  • Consider logging the deletions for auditing purposes.

Backup

  • Always back up your database before performing bulk deletions.
  • Test your code on a staging environment before applying it to your live site.

Automation and Scheduled Tasks

  • If you need to delete orders regularly, consider setting up a cron job to run your deletion script at specified intervals.

Conclusion

Deleting WooCommerce orders programmatically can greatly enhance your store management capabilities. By following the steps outlined in this blog post you can efficiently remove unwanted orders, automate routine tasks and maintain a clean and well-managed WooCommerce store. Always ensure to follow best practices to avoid unintended data loss and maintain the integrity of your store’s data.

If you have any questions or run into issues feel free to leave a comment below or reach out to the WooCommerce community for support. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *