
本文详解如何使用 WordPress 的 get_terms() 函数正确获取某父分类(如 product_cat)下的直接子分类,并通过 exclude 参数灵活排除指定 ID 的分类,避免常见参数传参错误。
本文详解如何使用 wordpress 的 `get_terms()` 函数正确获取某父分类(如 product_cat)下的直接子分类,并通过 `exclude` 参数灵活排除指定 id 的分类,避免常见参数传参错误。
在 WordPress 开发中,常需动态获取某个产品分类(如 product_cat)下的一级子分类用于导航、筛选或侧边栏展示。原始代码中直接以字符串 'parent=175' 传递参数的方式已过时且无法支持 exclude 等高级选项——get_terms() 自 WordPress 4.5 起仅接受关联数组形式的参数,旧式查询字符串语法已被弃用。
✅ 正确写法如下(以父分类 ID 175 为例,同时排除 ID 为 201、205 和 210 的子分类):
<?php $parent_id = 175;
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'parent' => $parent_id,
'hide_empty' => false, // 可选:是否隐藏无文章的分类
'exclude' => array( 201, 205, 210 ), // 要排除的分类 ID 数组
'fields' => 'all', // 确保返回完整对象(含 link 等信息)
) );
// 注意:get_terms() 在失败时返回 WP_Error 对象,建议检查
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return;
}
echo '
- ';
foreach ( $terms as $term ) {
$term_link = get_term_link( $term );
if ( is_wp_error( $term_link ) ) {
continue; // 跳过链接生成失败的项
}
echo '
- ' . esc_html( $term->name ) . ' '; } echo '
? 关键注意事项:
- exclude 参数必须传入整数 ID 组成的数组(如 array(123, 456)),不可传字符串或逗号分隔字符串;
- parent 值应为整数(非字符串 '175'),确保类型安全;
- 务必检查 get_terms() 返回值:空数组或 WP_Error 需提前处理,避免 foreach 报错;
- 若需排除的是“当前分类自身及其后代”,请改用 exclude_tree(支持层级排除);
- hide_empty => true 是默认行为,如需显示空分类,请显式设为 false。
该方案兼容 WooCommerce 产品分类体系,也适用于自定义分类法,是构建健壮、可维护分类导航的标准实践。











