WooCommerce产品更新Hook扩展:需支持REST API更新触发
Great question! The issue here is that the _edit_lock meta key isn't updated when a product is modified via the REST API — that meta field is specifically tied to the WordPress admin's post locking mechanism, which doesn't apply to API requests. That's why your current code only runs when updating products from the dashboard.
Better Hook for WooCommerce Product Updates
Instead of relying on updated_post_meta with _edit_lock, use the woocommerce_update_product hook. This is a WooCommerce-specific action that fires every time a product is updated, whether it's from the admin UI, REST API, or any other programmatic update. It's far more reliable for this use case.
Here's the revised code:
add_action( 'woocommerce_update_product', 'attach_variation_images_on_product_save', 10, 1 ); function attach_variation_images_on_product_save( $product ) { // Get the post ID from the product object if needed $post_id = $product->get_id(); // Your custom logic goes here // Example: Check if it's a variable product (if needed) if ( $product->is_type('variable') ) { // do something with variations } }
Why This Works
woocommerce_update_productpasses aWC_Productobject directly to your function, so you can easily access all product properties without extraget_post_typechecks.- It triggers for all product update events, including REST API PUT/PATCH requests, admin saves, and even bulk edits.
Alternative: REST API-Specific Hook
If you only want to run your logic when the product is updated via the REST API, you can use the rest_after_update_product hook instead:
add_action( 'rest_after_update_product', 'attach_variation_images_on_rest_product_save', 10, 3 ); function attach_variation_images_on_rest_product_save( $response, $post, $request ) { // $post is the WP_Post object of the updated product $post_id = $post->ID; // Your custom logic here }
Why Your Original Code Failed
The _edit_lock meta key is only set when a user starts editing a post in the WordPress admin. When you update a product via the REST API, there's no "lock" process involved, so that meta field never gets updated — hence your function never triggers.
内容的提问来源于stack exchange,提问作者Vpant

