首页 文章

在Woocommerce存档页面上显示特定的产品属性

提问于
浏览
3

我想在每个产品的商店商店页面上显示我选择的一些特定产品属性 . 必须显示属性的名称并与其值相反 . 我开始编写代码,我想打印至少名称,但我只显示最后一个属性的名称

add_action('woocommerce_after_shop_loop_item','add_attribute');
function add_attribute() {
    global $product;
    $weigth_val = $product->get_attribute('weight');
    $quant_val = $product->get_attribute('quantity');
    $length_val = $product->get_attribute('length');
    echo $weigth_val;
    echo $quant_val;
    echo $length_val;
}

1 回答

  • 6

    在woocommerce中,每个产品属性都是自定义分类,并记录在数据库中,将 pa_ 添加到其slugs的开头...

    该分类名称将与 WC_Product get_attribute() 方法一起使用 .

    所以你的代码应该是这样的:

    add_action('woocommerce_after_shop_loop_item','displaying_product_attributes');
    function displaying_product_attributes() {
        global $product;
    
        $weigth_val = $product->get_attribute('pa_weight');
        $quant_val  = $product->get_attribute('pa_quantity');
        $length_val = $product->get_attribute('pa_length');
    
        echo $weigth_val;
        echo $quant_val;
        echo $length_val;
    }
    

    它现在应该工作......


    要获得产品 attribute name label 并使用您将使用的产品的相应名称值:

    add_action('woocommerce_after_shop_loop_item','add_attribute');
    function add_attribute() {
        global $product;
    
        $product_attributes = array( 'pa_weight', 'pa_quantity', 'pa_length', 'pa_color' );
        $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_weight');
    
                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>';
    }
    

    代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .

相关问题