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

WordPress中get_terms获取指定父分类子项时如何排除特定分类

get_terms 添加exclude参数排除指定分类的正确写法

get_terms 的exclude参数接收待排除项的term ID组成的一维整数数组,从WordPress 4.5版本开始,统一使用数组格式传参是兼容性最好、最不容易出错的写法,不要混用旧的字符串拼接传参方式。

核心参数规则

  • exclude 只接受整数类型的分类ID,不支持传入分类名称、别名
  • 多分类排除直接把对应ID按顺序放进数组即可,不需要做特殊拼接
  • 原代码里直接count返回结果的写法缺少异常判断,建议补充is_wp_error校验,避免分类法失效时触发PHP报错

修改后可直接使用的代码

<?php
// 数组内替换为你实际需要排除的产品分类ID
$exclude_term_ids = [182, 195, 207];
$args = [
    'taxonomy'   => 'product_cat',
    'parent'     => 175,
    'exclude'    => $exclude_term_ids,
    'hide_empty' => false, // 按需调整,设为true则自动隐藏无商品的空分类
];
$terms = get_terms($args);

if (!is_wp_error($terms) && count($terms) > 0) {
    echo '<ul>';
    foreach ($terms as $term) {
        printf(
            '<li><a href="%s">%s</a></li>',
            esc_url(get_term_link($term)),
            esc_html($term->name)
        );
    }
    echo '</ul>';
}
?>

代码里额外加了esc_url和esc_html输出转义,是WordPress/WooCommerce开发的规范写法,可以避免XSS风险,可直接使用。

如果一定要用旧版字符串传参(不推荐,容易出现参数转义问题),写法是把exclude的ID用逗号拼接后写到参数字符串里:

// 旧版字符串传参示例(不推荐)
$terms = get_terms( 'product_cat', 'parent=175&exclude=182,195,207' );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 08:03:28