【问题标题】:Get product attribute labels from variations of a variable product in Woocommerce从 Woocommerce 中可变产品的变体中获取产品属性标签
【发布时间】:2019-03-08 13:59:10
【问题描述】:

我创建了一个示例 'woocommerce' 产品列表,然后单个产品页面没有获取产品的属性标签。下面显示代码

<?php if ( !$product->variations ) {return;}$field_name = isset($field_name) ? $field_name :'';$calendar_id = isset($calendar_id) ? $calendar_id : 0; <?php if ( $field_name ):?><?php foreach($product->variations as $variation_id => $variation_data):?><?php echo $variation_data['variation_title'];?><?php endforeach ?>

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy variations


    【解决方案1】:

    变量$field_name$calendar_id 没有在你的代码中定义,所以我不使用它们。

    自 Woocommerce 3 以来,您的代码似乎已经过时。从可变产品对象中,要获取变体属性标签名称/术语名称对,请使用以下内容:

    <?php 
    if ( $product->is_type('variable') && $variations = $product->get_available_variations() ) {
        $field_name  = isset($field_name)  ? $field_name  : '';
        $calendar_id = isset($calendar_id) ? $calendar_id :  0;
    
        if ( sizeof( $variations ) > 0 ) {
    
            // Loop through available product variations
            foreach( $variations as $variation ) {
    
                // Get variation title
                $variation_title = get_the_title( $variation['variation_id'] );
    
                // Display variation title
                echo '<p><strong>Title:</strong> ' . $variation_title . '</p>';
    
                // Loop through variation attributtes
                foreach( $variation['attributes'] as $variation_attribute => $term_slug ){
                    // Get attribute taxonomy name
                    $taxonomy   = str_replace( 'attribute_', '', $variation_attribute );
    
                    // Get attribute label name
                    $label_name = wc_attribute_label($taxonomy);
                    // Get attribute term name value
                    $term_name  = get_term_by( 'slug', $term_slug, $taxonomy )->name;
    
                    // Display attribute label / term name pairs
                    echo '<p><strong>' . $label_name . ':</strong> ' . $term_name . '</p>';
                }
            }
        }
    }
    ?>
    

    在 Woocommerce 3+ 中测试和工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-14
      • 2019-04-30
      • 2019-01-23
      • 1970-01-01
      • 2018-07-20
      • 2018-10-11
      • 1970-01-01
      • 2018-07-18
      相关资源
      最近更新 更多