使用 Woocommerce 中的挂钩更新产品价格
当产品在 wp-admin 中更新时,我尝试使用带有整数或字符串的元键 _regular_price
更新产品常规价格.
I am trying to update the the product regular price using the meta key _regular_price
with an integer or string when the product is updated in the wp-admin.
我想要的用户流程是:
- 打开产品编辑页面
- 点击更新按钮
- 看到页面重新加载后 _regular_price 设置为 20.
add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
update_post_meta( $post_id, '_regular_price', 20 );
}
请帮我找出我在上述函数中做错的地方,并告诉我任何其他方法来实现这一点.
Please help me find what I'm doing wrong in the above function and let me know of any other ways to accomplish this.
更新 (2018 年 8 月)
您的代码是正确的,但钩子是为 Metaboxes 自定义字段制作的.
Your code is correct but the hook is made for Metaboxes custom fields.
你应该使用 save_post_{$post->post_type}
Wordpress hook 仅针对产品帖子类型.
You should use instead save_post_{$post->post_type}
Wordpress hook targeting product post type only.
此外,您可能需要使用wc_delete_product_transients()
.
Also You may need to update the active price and to refresh the product transient cache with the function wc_delete_product_transients()
.
所以你的代码将是:
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 文件或任何插件文件中.
经过测试并有效......
Tested and works…