php - 更新 Woocommerce 中可变产品的所有变体价格

标签 php wordpress woocommerce product product-variations

我需要循环获取所有变体 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

根据您使用此代码的位置方式,您应该首先尝试包括global $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+ 上测试并有效

关于php - 更新 Woocommerce 中可变产品的所有变体价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664066/

相关文章:

php - 通过 PHP 和 MySqL 进行数据替换触发

php - 如何从 php 变量中获取数据属性?

jquery - 悬停在 js 生成的类/元素上不起作用

wordpress - wordpress 上的调试日志不起作用

php - 如何从wordpress网站获取json响应

css - 尝试选择没有自己类别的特定链接

wordpress - 如果为空,则删除 Woocommerce 评论选项卡

javascript - 无法读取我的 WordPress 插件上 null 的属性 '1'

css - Woocommerce 电话号码输入字段从右到左

php - undefined index id、fname、lastname 在 php 中