当产品在 wp-admin 中更新时,我尝试使用带有整数或字符串的元键 _regular_price
来更新产品常规价格。
我想要的用户流程是:
- 打开产品编辑页面
- 点击更新按钮
- 页面重新加载后,您会看到 _regular_price 设置为 20。
add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
update_post_meta( $post_id, '_regular_price', 20 );
}
请帮我找出我在上述函数中做错了什么,并让我知道完成此操作的任何其他方法。
最佳答案
已更新 (2018 年 8 月)
您的代码是正确的,但 Hook 是为 Metaboxes 自定义字段制作的。
您应该使用 save_post_{$post->post_type}
WordPress Hook 仅定位产品帖子类型。
此外,您可能需要使用函数 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 文件中或任何插件文件中。
经过测试并有效...
关于php - 使用 WooCommerce 中的 Hook 更新产品价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47277671/