Johano Fierra
Johano Fierra

Reputation: 935

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...

Upvotes: 7

Views: 11328

Answers (2)

honk31
honk31

Reputation: 4347

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..

Upvotes: 8

bWlrYWphdWhvbmVu
bWlrYWphdWhvbmVu

Reputation: 1774

Check your error log. Should be some info there. If I am looking at the correct action it takes four arguments:

do_action( 'woocommerce_order_edit_product', $this->id, $item_id, $args, $product );

So your code should be:

add_action('woocommerce_order_edit_product', 'your_function_name', 10, 4);
function your_function_name($id, $item_id, $args, $product){
//my php function code would be here
}

Upvotes: 0

Related Questions