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

如何在指定页面展示WooCommerce商品属性全术语及关联商品数(含空术语)

WooCommerce 属性术语(含空术语)带商品数量展示方案

短代码方案(推荐)

这个短代码支持指定任意WooCommerce商品属性,输出所有术语(包括无关联商品的空术语),并标注每个术语的关联商品数量:

function display_attribute_terms_shortcode($atts) {
    $atts = shortcode_atts(array(
        'attribute' => '',
    ), $atts);

    if (empty($atts['attribute'])) {
        return '<p>请指定WooCommerce商品属性的slug(例如:pa_color)</p>';
    }

    $taxonomy = wc_attribute_taxonomy_name($atts['attribute']);
    if (!taxonomy_exists($taxonomy)) {
        return '<p>指定的属性不存在</p>';
    }

    $terms = get_terms(array(
        'taxonomy' => $taxonomy,
        'hide_empty' => false,
        'orderby' => 'name',
        'order' => 'ASC',
    ));

    if (empty($terms)) {
        return '<p>该属性没有任何术语</p>';
    }

    $output = '<h3>' . wc_attribute_label($atts['attribute']) . '</h3>';
    $output .= '<ul>';
    foreach ($terms as $term) {
        $output .= '<li>' . esc_html($term->name) . ' (' . intval($term->count) . ')</li>';
    }
    $output .= '</ul>';

    return $output;
}
add_shortcode('display_attribute_terms', 'display_attribute_terms_shortcode');

使用方法:

  • 将代码添加到WordPress主题的functions.php文件,或用Code Snippets插件管理(避免主题更新丢失代码)。
  • 在目标页面/文章中插入短代码:[display_attribute_terms attribute="pa_color"],替换pa_color为你实际的商品属性slug(WooCommerce属性slug默认以pa_开头)。

自定义PHP代码片段(直接嵌入模板)

如果需要直接在主题模板(如page.php、single-product.php)中展示,可使用以下代码:

// 替换为目标商品属性的slug
$attribute_slug = 'pa_color';
$taxonomy = wc_attribute_taxonomy_name($attribute_slug);

if (taxonomy_exists($taxonomy)) {
    $terms = get_terms(array(
        'taxonomy' => $taxonomy,
        'hide_empty' => false,
        'orderby' => 'name',
        'order' => 'ASC',
    ));

    if (!empty($terms)) {
        echo '<h3>' . wc_attribute_label($attribute_slug) . '</h3>';
        echo '<ul>';
        foreach ($terms as $term) {
            echo '<li>' . esc_html($term->name) . ' (' . intval($term->count) . ')</li>';
        }
        echo '</ul>';
    } else {
        echo '<p>该属性没有任何术语</p>';
    }
} else {
    echo '<p>指定的属性不存在</p>';
}

使用方法:将代码粘贴到你想要展示内容的模板位置,替换pa_color为目标属性slug即可。


插件方案(无需写代码)

  1. Code Snippets:安装激活后,将上述短代码代码添加到插件中并启用,之后就能在页面/文章中使用短代码展示。
  2. Term Management Tools:轻量插件,支持管理所有属性术语,包括查看空术语的商品数量,可通过插件自带的功能或短代码实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:16:07