Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce hook for order update

Good morning everyone. As the title says I'm trying to fire a function when an order is updated. More specifically I want to run this function when a custom field in the order page (admin side) is changed and then saved.

I'm not looking to find out when an order is complete or when its status is updated, but just when this field is updated.

Currently I'm using woocommerce_process_shop_order_meta hook but it doesn't seem to work.

Any advice?
Thank you!

-- EDIT --

woocommerce_process_shop_order_meta is the righ hook to use, I was having an error in the function triggered by this hook so if you ever need to run a function after you click update order in the admin page this is the right way to do it.

like image 431
Andrea Avatar asked Apr 15 '16 12:04

Andrea


2 Answers

As written in the edit the woocommerce_process_shop_order_meta is the right hook to use if you want to trigger a function or a response when an order is update.

like image 86
Andrea Avatar answered Nov 11 '22 14:11

Andrea


I ended up using the save_post_shop_order hook. It is called on the following events:

  • order creation (both customer checkout process & admin)
  • single order update
  • bulk status update
  • trashing the order
  • untrashing the order

For watching only order updates, you have to filter out non-order type posts and post creations like so:

add_action (
    'save_post_shop_order',
    function (int $postId, \WP_Post $post, bool $update): void
    {
        // Ignore order (post) creation
        if ($update !== true) {
            return;
        }

        // Here comes your code...
    },
    10,
    3
);

The woocommerce_after_order_object_save seemed to be a good choice first, but in my experience it runs 3 times on a single order update (in a simple, factory install without plugins). At the time of the first 2 runs, the order data wasn't even up to date (the status was the one before the update), so I find this hook useless.

like image 42
Márton Tamás Avatar answered Nov 11 '22 13:11

Márton Tamás