简体   繁体   中英

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.

如编辑中所写, woocommerce_process_shop_order_meta是正确的钩子,如果您想在订单更新时触发函数或响应。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM