0

I used the hook {status}_{post_type} from the docs here.

In the docs it said: action will execute when a post of type {post_type} transitions to {status} from any other status.

Here is my code:

function on_order_on_hold( $ID, $post) {
    # do some job
}
add_action('wc-on-hold_shop_order', 'on_order_on_hold', 10, 2);

And it run when the order transition from wc-on-hold to any other status, instead of to wc-on-hold from any other status.

Is the docs wrong or I misunderstand something here?

Thank you in advance.

1 Answer 1

0

WooCommerce has its own hooks for things like this. You shouldn't rely on the underlying WordPress post-related hooks and functions when dealing with products and orders.

WooCommerce is moving towards using custom database tables for products and orders instead of custom post types and while there'll be hooks etc. added for backwards compatibility, you'll be much better situated for that transition if you use WooCommerce's APIs.

WooCommerce has 3 hooks for handling order status transitions:

woocommerce_order_status_{status} runs when transitioning to {status} from any other status.

woocommerce_order_status_{from}_to_{to} runs when transitioning to status {to} from status {from}

woocommerce_order_status_changed runs when there's any transition change and receives the from and to status as the 2nd and 3rd callbacks of the callback respectively.

Note that the status in all these hooks should omit the wc- prefix.

function wpse_313075_order_on_hold( $order_id, $order ) {
    // Do something.
}
add_action( 'woocommerce_order_status_on-hold', 'wpse_313075_order_on_hold', 10, 2 );

function wpse_313075_order_pending_to_on_hold( $order_id, $order ) {
    // Do something.
}
add_action( 'woocommerce_order_status_pending_to_on-hold', 'wpse_313075_order_pending_to_on_hold', 10, 2 );

function wpse_313075_order_status_changed( $order_id, $from, $to, $order ) {
    // Do something.
}
add_action( 'woocommerce_order_status_changed', 'wpse_313075_order_status_changed', 10, 4 );
3
  • Thank you for your answer, it is very useful. Even though, I think underlying WordPress post-related should be correct as well.
    – Hà Link
    Sep 1, 2018 at 10:57
  • Well it's not best practice, and it only means you might have issues in the future when products and shop orders are no longer posts. This is not far away. Sep 1, 2018 at 11:00
  • I have to thank you one more time for this valuable information. I will use these hooks instead.
    – Hà Link
    Sep 1, 2018 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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