You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce商品列表页自定义属性显示问题求助

问题:WooCommerce商品列表页自定义属性显示为空

我希望在网站的WooCommerce商品列表页显示location和date两个属性。找到现有代码后,尝试将$taxonomy = 'pa_country';修改为$taxonomy = 'pa_location';来实现需求,但仅能显示标签,属性内容为空,求解决办法。

原代码如下:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
global $product;
if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_country';
    echo '<span class="attribute-s">Country: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_class';
    echo '<span class="attribute-s">Class: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_faction';
    echo '<span class="attribute-s">Faction: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}
 if ( $product->is_type('simple') ) {
    $taxonomy = 'pa_gender';
    echo '<span class="attribute-s">Gender: ' . $product->get_attribute($taxonomy) . '</span>','<br>';
}}

解决步骤

1. 排查核心问题

  • 确认属性分类法名称:WooCommerce产品属性的分类法名称是pa_+属性slug,先进入后台「WooCommerce → 产品 → 属性」,找到location和date属性查看slug字段,确保是location和date,对应分类法就是pa_location和pa_date。
  • 检查商品属性赋值:编辑目标简单商品,在「产品数据 → 属性」选项卡中,确认已为location和date属性设置了值,且属性已关联到该商品。
  • 清理网站缓存:如果用了缓存插件,修改代码后务必清理缓存,避免旧代码残留。

2. 优化后的代码

下面是整合了location和date属性显示的优化代码,简化了重复判断逻辑,还增加了值为空时不输出的判断:

add_action( 'woocommerce_after_shop_loop_item_title', 'display_custom_product_attributes', 5 );
function display_custom_product_attributes() {
    global $product;

    // 仅处理简单类型商品
    if ( ! $product->is_type('simple') ) {
        return;
    }

    // 定义要显示的属性:键=分类法名称,值=前端显示的标签
    $attributes = array(
        'pa_location' => 'Location',
        'pa_date'     => 'Date',
        'pa_class'    => 'Class',
        'pa_faction'  => 'Faction',
        'pa_gender'   => 'Gender'
    );

    // 循环输出每个属性
    foreach ( $attributes as $taxonomy => $label ) {
        $attr_value = $product->get_attribute($taxonomy);
        // 仅当属性有值时才输出
        if ( ! empty($attr_value) ) {
            echo '<span class="attribute-s">' . esc_html($label) . ': ' . esc_html($attr_value) . '</span><br>';
        }
    }
}

内容的提问来源于stack exchange,提问作者ReflectedReality

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:20:36