Updated (2018年8月)
您的代码是正确的,但该挂钩是为 Metaboxes 自定义字段制作的。
你应该使用save_post_{$post->post_type} https://developer.wordpress.org/reference/hooks/save_post_post-post_type/WordPress 钩子仅定位产品帖子类型.
此外,您可能需要更新有效价格和刷新产品临时缓存与功能wc_delete_product_transients() https://docs.woocommerce.com/wc-apidocs/source-function-wc_delete_product_transients.html#135-181.
所以你的代码将是:
add_action( 'save_post', 'update_the_product_price', 10, 3 );
function update_the_product_price( $post_id, $post, $update ) {
if ( $post->post_type != 'product') return; // Only products
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( ! current_user_can( 'edit_product', $post_id ) )
return $post_id;
$price = 50; // <=== <=== <=== <=== <=== <=== Set your price
$product = wc_get_product( $post_id ); // The WC_Product object
// if product is not on sale
if( ! $product->is_on_sale() ){
update_post_meta( $post_id, '_price', $price ); // Update active price
}
update_post_meta( $post_id, '_regular_price', $price ); // Update regular price
wc_delete_product_transients( $post_id ); // Update product cache
}
代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
经过测试并有效...