且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-26 23:09:22

在woocommerce中,每个产品属性为自定义分类法,并记录在数据库中,将 pa _ 添加到子句的开头……

In woocommerce each product attribute is a custom taxonomy and are recorded in database adding pa_ to the beginning of their slugs…

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

That taxonomy name is to be used with WC_Product get_attribute() method.

因此,您的代码应改为:

So so your code should be instead:

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

现在应该可以工作了……

It should work now…

要获取产品属性名称标签,并使用产品的相应名称值,您将使用:

To get the product attribute name label and with the corresponding name value for products you will use:

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文件)。经过测试,可以正常工作。

Code goes in function.php file of your active child theme (or active theme). Tested and works.