【问题标题】:Get weight value from WooCommerce variations of a variable product从可变产品的 WooCommerce 变体中获取重量值
【发布时间】:2021-01-13 18:57:06
【问题描述】:

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

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() 当然不起作用,所以我想知道从变体中获取属性是否完全错误?

【问题讨论】:

    标签: php wordpress methods woocommerce product-variations


    【解决方案1】:

    使用WC_Variable_Productget_visible_children()(或get_children()方法,试试:

    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_Productget_available_variations()如下:

    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>';
            }
        }
    }
    

    两种代码 sn-p 都有效。

    【讨论】:

    • 很好的答案!我看到我对于权重变量的层太深了。我使用了下半部分,因为它更容易弹出,但上半部分是获取不同数据的绝佳参考。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2019-03-08
    • 2018-07-20
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    • 2018-01-27
    相关资源
    最近更新 更多