Automating WooCommerce Order Status Changes

WooCommerce-order-status-change

I run a WooCommerce site where I sell a plugin that helps create personalized URLs. It's called ElegantPURL and it's pretty nifty, if you're into that sort of thing. But because it's a digital download, I've always seen the same thing when it comes to Order Status. It's always “completed.”

Why are the order statuses not “completed?”

The other day (a couple of weeks ago by now), a friend posted a tweet asking if there was a way to automatically change the order status to complete after a payment had been received. That's because it does it already for downloads but doesn't do it for other product types. So the WooCommerce order status doesn't stay as ‘current' as it should.

And while there's no magical check box to mark, it's actually pretty easy. Today I thought I'd show you what you need to know.

Creating a Simple Function & Connecting It

The first thing to note is that there's a hook you can leverage already coded up in the WooCommerce plugin. It's called woocommerce_payment_complete_order_status. That's what you'd connect your function to, so that you could adjust the status right after payment was completed.

NOTE: any time we're talking about code, you should evaluate whether you really want to put it into your functions.php file, or into a plugin container to keep it separate from your theme.

So we'd start with a simple add_filter.

add_filter (‘woocommerce_payment_complete_order_status', ‘my_change_status_function');

If you are unfamiliar with adding a filter, you can check the codex here.

Now we need to create that function.

function my_change_status_function ($order_id) {
$order = new WC_Order($order_id);
//Do whatever additional logic you like before….
return ‘completed';
}

Should you do more than that? Well, it might be nice to make sure the order status was in a status you were expecting (only the ones you were expecting), but that's about it.

Now place the code somewhere special

So you take this code and either put it in your functions.php file, or wherever your theme wants this kind of code. And soon, every single order that's been paid for will automatically have their orders marked as complete.

What do you do now?

So if you have that in place and working, you might wonder, what to do now? Well, what about kicking off some crazy activity tied to the fact that your order status just changed (right after your payment status cleared)?

Guess what? There's a hook for that too!

add_action( ‘woocommerce_order_status_completed', ‘my_post_order_status_change_function' );

So what are you waiting for? Go do some crazy stuff!