2
votes

Is there a hook I can use when I make a change to someone's order via the admin (such as their address, or a custom meta field)? I read this question but unfortunately woocommerce_process_shop_order_meta is fired before the order is saved, meaning I have no access to the newly updated data. What I need is to be able to use the new data that is saved to the order.

UPDATE: An issue with using save_post_shop_order is that the meta is updated before this is hit, so I can't compare the previously saved meta value, for example:

$metaArray = $_POST['meta'];

foreach($metaArray as $meta => $key) {
    $metaArr[$key["key"]] = $key["value"];
}

$meta = get_post_meta($order->ID);

if($meta['coverstart'][0] != $metaArr['coverstart']) {
    die("COVER START DATE HAS CHANGED");
}

The die() is never hit, because the script always gets the newly saved value.

1
Does this answer your question? Woocommerce hook for order updateMárton Tamás

1 Answers

2
votes

Sorry but woocommerce_checkout_update_order_meta is fired after the order is saved… See this extract source code located in WC_Checkout create_order() method:

// Save the order.
$order_id = $order->save(); // <== Order is saved here before

do_action( 'woocommerce_checkout_update_order_meta', $order_id, $data ); <== // The hook

return $order_id;

So in woocommerce_checkout_update_order_meta you can get the saved order data:

  • by retrieving the WC_Order object from the $order_id argument and using all methods on it.
  • or using get_post_meta() on with the $order_id argument to get the data saved in wp_postmeta database table.

Then you can update the data with update_post_meta() function…


You can even use woocommerce_checkout_create_order before the data is saved…

You will be able to get the data from the $order argument using all available methods for the WC_Order class (CRUD getters methods).

You will be able to alter this data and saving it using the CRUD setters methods…

Some examples in stackOverFlow


If you need to do that after the order process the hooks to be used can be:

  • woocommerce_new_order (on newly created order event)
  • woocommerce_thankyou (on order received page)
  • woocommerce_order_status_changed (on order status changing event)

And may be some others…


To alter the data when order is saved in backend, you will use save_post_shop_order that has 3 arguments: $post_id, $post and $update