在Woocommerce存档页面上显示特定的产品属性 [英] Display specific product attributes on Woocommerce archives pages

查看:152
本文介绍了在Woocommerce存档页面上显示特定的产品属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to display some specific product attributes of my choice on the store shop page for each product. It is necessary to display the name of the attribute and opposite its value. I started writing code, I wanted to print at least names, but I only show the name of the last attribute

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


推荐答案

在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.

这篇关于在Woocommerce存档页面上显示特定的产品属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆