WooCommerce hook on order status change fires multiple times instead for only the changed order

730 Views Asked by At

I've created a hook for WooCommerce when an order is cancelled like so:

add_action( 'woocommerce_order_status_cancelled', 'prefix_order_cancelled_hook' );

function prefix_order_cancelled_hook($order_id){
    write_log("Order ${order_id} has been cancelled")
}

Now when the status changed to cancelled, the hook is invoked as expected but the output execution is not what I'm expecting. I'm getting the following in the log:

Order 4 has been cancelled
Order 5 has been cancelled
Order 6 has been cancelled

I've seen that this corresponds to the number of orders I currently have on the store. Can someone help with why this is happening and how to only run the hook once for the changed order.

1

There are 1 best solutions below

1
On

Seems like your code is executed for all orders. So there seems to be a problem with the $order_id. I think you can't access properties directly, but need to get an instance of the WC_Order object (since Woocommerce 3.0+ something about) like:

add_action( 'woocommerce_order_status_cancelled', 'prefix_order_cancelled_hook' );

function prefix_order_cancelled_hook($order_id){
    // get an instance of an WC_Order object
    $order = wc_get_order( $order_id );
    // get the ID of the order
    $order_id = $order->get_id();
    write_log("Order ${order_id} has been cancelled")
}