更新Woocommerce中可变产品的所有变异价格 [英] Update all variations prices of a variable product in Woocommerce
问题描述
我需要获取所有版本ID并循环更新价格. 简单的查询和循环看起来像:
I need to get all variation id and update price in loop. Simple query and loop looks like:
$params = array(
‘posts_per_page’ => -1,
‘post_type’ => ‘product_variation’,
‘post_parent’ => $product->get_id() // tried $post-ID
);
$variations = get_posts( $params );
foreach ( $variations as $variation ) {
$variation_ID = $variation->ID; // tried $post-ID, $product->get_id()
$regular_price=34;
update_post_meta( $variation_ID, ‘_regular_price’, (float)$regular_price );
update_post_meta( $variation_ID, ‘_price’, (float)$regular_price );
}
我认为这不起作用:
(‘post_parent’ => $product->get_id())
或者这个:
($variation_ID = $variation->ID;).
推荐答案
代码中的第一位
‘
或’
应该替换为'
. 另外,如果使用$post-ID
,也应将其替换为$post->ID
First in your code
‘
or’
should be replaced by'
. Also if used$post-ID
should be replaced by$post->ID
根据您使用此代码的位置和方式,应首先尝试包含global $post;
,以便能够使用WP_Post
对象$post
Depending on where and how you are using this code, you should try to include global $post;
first to be able to use the WP_Post
object $post
.
然后,您可以尝试使用此自定义的代码版本:
Then you could try to use this customized version of your code instead:
global $post;
$regular_price = 13;
// Only for product post type
if( $post->post_type == 'product' )
$product = wc_get_product( $post->ID ); // An instance of the WC_Product object
// Only for variable products
if( $product->is_type('variable') ){
foreach( $product->get_available_variations() as $variation_values ){
$variation_id = $variation_values['variation_id']; // variation id
// Updating active price and regular price
update_post_meta( $variation_id, '_regular_price', $regular_price );
update_post_meta( $variation_id, '_price', $regular_price );
wc_delete_product_transients( $variation_id ); // Clear/refresh the variation cache
}
// Clear/refresh the variable product cache
wc_delete_product_transients( $post->ID );
}
此代码已在WooCommerce 3+及更高版本上经过测试
This code is tested on WooCommerce version 3+ and works
这篇关于更新Woocommerce中可变产品的所有变异价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!