php - 在 Woocommerce 文件页面上显示特定的产品属性

标签 php wordpress woocommerce product custom-taxonomy

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

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_ 添加到其 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;
}

它现在应该可以工作了......


获取产品属性名称标签以及您将使用的产品的相应名称值:

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 文件。经过测试并有效。

关于php - 在 Woocommerce 文件页面上显示特定的产品属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49630032/

相关文章:

php - 在 WordPress 中处理表单的 PHP 文件应该保存在哪里?

php - 为什么我得到笛卡尔积而不是连接?

javascript - Wordpress Envira Gallery 不会以禁止状态加载

linux - 我应该将用户添加到 apache 组吗

wordpress - 当产品添加到购物车时,woocommerce 获取产品 ID

php - WooCommerce 自定义产品验证

php - MySQL -- fatal error : Call to a member function bind_param() on a non-object

PHP Mysql 为我的网站中的新注册用户创建文件夹和新数据库

php - 将 css 的 url 站点更改为一致的

wordpress - 问题仅允许 WooCommerce 购物车中的一种产品