在特定的Woocommerce产品类别档案页面上显示产品属性

时间:2018-11-28 01:24:42

标签: php wordpress woocommerce product custom-taxonomy

我想在类别页面上显示两个属性,仅在特定类别上显示属性名称和值。

我找到的这段代码显示了属性的标签,但是正在复制值,并且我真的很努力地查看是否有category变量。任何帮助是极大的赞赏。

screenshot

代码:

add_action('woocommerce_after_shop_loop_item','add_attribute');
function add_attribute() {
    global $product;

    $product_attributes = array( 'pa_set', 'pa_team');
    $attr_output = array();

    // Loop through the array of product attributes
    foreach( $product_attributes as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
            $value = $product->get_attribute('pa_set');

               if( ! empty($value) ){
                // Storing attributes for output
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': 
    '.$value.'</span>';
            }
        }
    }

    // Output attribute name / value pairs separate by a "<br>"
    echo '<div class="product-attributes">'.implode( '<br>', $attr_output 
    ).'</div>'; 
}

1 个答案:

答案 0 :(得分:0)

已更新-问题来自以下行,其中产品属性属性值始终用于同一产品属性:

$value = $product->get_attribute( 'pa_set' );

,应该改为:

$value = $product->get_attribute( $taxonomy );

完整的重新审阅代码将是:

add_action('woocommerce_after_shop_loop_item','display_loop_product_attribute' );
function display_loop_product_attribute() {
    global $product;

    $product_attributes = array('pa_set', 'pa_team'); // Defined product attribute taxonomies.
    $attr_output = array(); // Initializing

    // Loop through the array of product attributes
    foreach( $product_attributes as $taxonomy ){
        if( taxonomy_exists($taxonomy) ){
            if( $value = $product->get_attribute($taxonomy) ){
            // The product attribute label name
            $label_name = get_taxonomy( $taxonomy )->labels->singular_name;
                // Storing attributes for output
                $attr_output[] = '<span class="'.$taxonomy.'">'.$label_name.': '.$value.'</span>';
            }
        }
    }
    // Output attribute name / value pairs separate by a "<br>"
    echo '<div class="product-attributes">'.implode('<br>', $attr_output).'</div>';
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。


定位产品类别归档页面:

您将在函数内的IF语句上使用the conditional tag is_product_category()……

对于特定的产品类别归档页面,您可以在数组中的函数内as explained here进行设置,例如:

if( is_product_category( array('chairs', 'beds') ) {
    // Here go the code to be displayed
}

您只需要在数组中设置正确的产品类别标签...


相关:Show WooCommerce product attributes in custom home and product category archives

相关问题