Woocommerce hook that fires after a product is updated via REST API

时间:2018-04-20 21:31:53

标签: woocommerce hook-woocommerce woocommerce-rest-api

I am using this hook to run some code after the product is updated:

add_action( 'updated_post_meta', 'attach_variation_images_on_product_save', 10, 4 );
function attach_variation_images_on_product_save( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( $meta_key == '_edit_lock' ) { 
        if ( get_post_type( $post_id ) == 'product' ) {
           //do something
        }
    }
}

This is working as expected, the function is executed after the product is updated. I want to run the same function when a product is getting updated via the REST API. I hooked my function to woocommerce_rest_insert_product_object like this but it did not work:

 add_action( 'woocommerce_rest_insert_product_object', 'attach_variation_images_on_product_update_via_rest', 10, 3 ); 
function attach_variation_images_on_product_update_via_rest( $post, $request, $true ) {
    if ( get_post_type( $post ) == 'product' ) {
        $product = wc_get_product( $post );
        //do something
    }
}

Am I not using the right hook? Is there another hook I can use?

EDIT 1: It seems that my code was not running because get_post_type($post) is type of post and not product. I am trying to attach an image to variations using add_post_meta($variation_id, '_thumbnail_id', $image_id); inside a loop. It seems the function attach_variation_images_on_product_update_via_rest( $post, $request, $true ) is executed till the end but it does not attach the image to the variations.

1 个答案:

答案 0 :(得分:1)

当你从Woocommerce后端以及REST API更新产品时,我最终使用了执行回调函数的钩子add_action( 'woocommerce_update_product', 'my_callback_function', 10, 1 );