首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从变量产品的WooCommerce变化中获得权重值

从变量产品的WooCommerce变化中获得权重值
EN

Stack Overflow用户
提问于 2021-01-13 18:57:06
回答 1查看 1.3K关注 0票数 2

我正在开发一个自动调整产品价格的插件。我所有的产品都是可变的产品,这使得我解决不了这个问题。

代码语言:javascript
复制
if( $product->is_type( 'variable' ) ){
                           
  foreach ( $product->get_available_variations() as $key => $variation ) {
                                
    foreach ($variation['attributes'] as $attribute ) {

      if ( ! $attribute->get_weight() ) {

我有一个检查,以确保产品是可变的。唯一的产品属性是“大小”。这里我有4-8种不同尺寸的产品。它们中的每一个都有一个权重值,这似乎是Woocommerce实现的默认值。我无法从每一个变化中获得权重。出于好奇,我是否从错误的位置调用了get_weight(),或者是否存在不同的方法。get_weight()当然不起作用,所以我想知道从变体中获取属性是否完全错误?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-13 20:46:22

使用WC_Variable_Product get_visible_children() (或get_children()__)方法,尝试:

代码语言:javascript
复制
global $product; // If needed | or $product = wc_get_product( $product_id );

if( $product->is_type( 'variable' ) ){
    foreach ( $product->get_visible_children() as $variation_id ) {
        $variation = wc_get_product( $variation_id ); // Get the product variation object
        $weight    = $variation->get_weight(); // Get weight from variation

        if ( ! $weight ) {
            echo '<div>' __("No weight") . '</div>';
        } else {
            echo '<div><strong>' __("Weight") . ':</strong> ' . wc_format_weight( $weight ) . '</div>';
        }
    }
}

也可以使用WC_Variable_Product get_available_variations(),如下所示:

代码语言:javascript
复制
global $product; // If needed | or $product = wc_get_product( $product_id );

if( $product->is_type( 'variable' ) ){
    foreach ( $product->get_available_variations() as $key => $variation_data ) {
        $weight = $variation_data['weight']; // Get weight from variation

        if ( ! $weight ) {
            echo '<div>' __("No weight") . '</div>';
        } else {
            echo '<div><strong>' __("Weight") . ':</strong> ' . $variation_data['weight_html'] . '</div>';
        }
    }
}

这两个代码片段都能工作。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65708223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档