Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce: hook when saving changes to product in an order

I have been searching for hours...

I can't figure out how get a function to be executed when clicking "save" after editing the quantity of a product in an existing order.

I tried this:

add_action('woocommerce_order_edit_product', 'your_function_name');
function your_function_name(){
//my php function code would be here
}

but the your_function_name function is not being called when clicking save.

I tested the function and when calling it directly it works as it should, so I think I got the wrong hook...

like image 795
Johano Fierra Avatar asked Jan 28 '15 21:01

Johano Fierra


1 Answers

after wrestling with this issue for 2 days now, i found it: there is two hooks, one before and one after saving:

  1. woocommerce_before_save_order_items
  2. woocommerce_saved_order_items

both are fired when saving an order in the backend. one before the save and one afterwards.

both two hooks carry the same variables: $order_id (int) & $items (array)

i guess with the first hook, you could get the old order and compare its contents with the items array to see what has changed. at least this is what i try to accomplish now.

so this is how you would trigger this:

add_action( 'woocommerce_before_save_order_items', 'so42270384_woocommerce_before_save_order_items', 10, 2 );
function so42270384_woocommerce_before_save_order_items( $order_id, $items ) {
    echo $order_id;
    var_dump( $items );
}

be aware..

adding a product to an exitsting order does implement another hook that gets called before this (so when hitting SAVE, the above function will fire, but the order and its items are already set BEFORE saving (when adding a product, the order will save immediately). that means $order = new WC_Order( $order_id ); will have the new items already in it, before and after, so there is no way to find, what has changed.). but the woocommerce_ajax_add_order_item_meta hook is triggered on 'add product' and helped me on that end. happy coding everyone..

like image 124
honk31 Avatar answered Oct 27 '22 20:10

honk31