How to change order status in WooCommerce programmatically

For this week’s snippet, we will look at how to change the order status in WooCommerce programmatically.

It is probably one of the more common tasks you will need to do when building custom functionality into WooCommerce.

Luckily for us, it is super easy. WooCommerce provides a builtin function called update_status().

Here is the basic syntax of how to use it…

$order->update_status($status, $note, $manual)
  • $order is the WooCommerce order object
  • $status is the order status you want to change to (i.e. ‘completed’, ‘processing’, etc). You do not need to add the ‘wc-‘ prefix
  • $note is an optional parameter to add an order note after changing status
  • $manual is an optional parameter to specify if the update was done by a user or not. It is boolean (i.e. true or false), and is set to ‘false’ by default.

If you don’t need to add an order note, you can ignore the last two parameters ($note and $manual) and simply write something like $order->update_status('completed')

Let’s look at a more concrete example of how to use this function.

Example snippet: Change order status programmatically to “Completed”

In this basic example, whenever an order status is set to “Processing”, it will automatically be changed to “Completed”. We will use the action hook woocommerce_order_status_processing which gives us the order ID as a parameter.

add_action( 'woocommerce_order_status_processing', 'change_order_status', 10, 1);

function change_order_status( $order_id ) {

    // 1. get order object from order id
    $order = wc_get_order( $order_id );

    // 2. update status to completed
    $note = "Automagically completed; "; // optional
    $manual = true; // optional -- 'true' will show the username in the order notes
    $order->update_status('completed', $note, $manual); 

    // if you don't need to add a custom order note, simply write ... $order->update_status('completed')
    // ... that's it!  

}

Result:

Result if $manual = false (there is no username specified under note):

Not sure the situation you would use this snippet. Perhaps, you don’t need to ship/process anything, and just want the order to complete by itself. If you were actually using this snippet, you would probably also want to disable the “Processing order” email that is sent to customers.

You can also use the update_status() function with any custom order statuses you’ve created. You don’t need to include the ‘wc-‘ prefix. E.g: $order->update_status('shipped')

For example, you could build a function to automatically update the status to ‘Shipped’ after adding a tracking number.

πŸ€“

Get Weekly WordPress tips

Was this helpful? Every week, I post a useful tip about WordPress development. Subscribe below to get updates by email. (It's free πŸ™‚)

Leave a Comment