从Woocommerce中的可变产品变体获取产品属性标签

时间:2018-10-03 10:44:42

标签: php wordpress woocommerce custom-taxonomy variations

我创建了一个示例“ 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 ?>

1 个答案:

答案 0 :(得分:0)

  

变量$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+中经过测试并可以工作