微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 更新Woocommerce中变量产品的所有变化价格

我需要获取所有变体ID并在循环中更新价格.
简单的查询和循环看起来像:

$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;). 

解决方法:

First in your code or should be replaced by '.
Also if used $post-ID should be replaced by $post->ID

根据您使用此代码的位置和方式,您应该尝试包含全局$post;首先要能够使用WP_Post对象$post.

然后,您可以尝试使用此代码自定义版本:

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上进行测试并且有效

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐