WordPress中如何动态显示特定分类列表(排除指定分类)
WordPress 分类动态显示:排除指定分类并自动包含新增分类
需求说明
需实现分类列表动态展示:仅排除特定几个分类(如示例中的D、E),后续新增的分类自动加入显示列表,无需手动修改代码。
已尝试的代码
方法1:使用get_terms查询
$terms = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => true, 'number' => $per_page, 'offset' => $offset, 'parent' => 10 ) );
方法2:遍历分类并过滤单个分类
foreach((get_the_category()) as $category) { if($category->cat_name == "large-post") { } else { $cats .= $category->cat_name . ', '; } } echo rtrim($cats, ', ');
解决方案
方法1:利用get_terms的exclude参数(推荐)
直接在查询参数中指定要排除的分类ID,查询时自动跳过这些分类,新增分类只要不在排除列表就会被包含:
// 定义要排除的分类ID列表,替换为你的目标分类ID $exclude_category_ids = array(12, 15); $terms = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => true, 'number' => $per_page, 'offset' => $offset, 'parent' => 10, 'exclude' => $exclude_category_ids // 新增排除参数 ) );
若不知道分类ID,可通过分类slug获取:
// 通过slug获取要排除的分类ID $exclude_slugs = array('d-category', 'e-category'); $exclude_ids = array(); foreach($exclude_slugs as $slug) { $cat = get_category_by_slug($slug); if($cat) { $exclude_ids[] = $cat->term_id; } } $terms = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => true, 'number' => $per_page, 'offset' => $offset, 'parent' => 10, 'exclude' => $exclude_ids ) );
方法2:遍历所有分类并过滤排除项
如果需要更灵活的过滤逻辑,可先获取全部分类,再排除指定项:
// 定义要排除的分类slug $exclude_slugs = array('d-category', 'e-category'); $all_terms = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => true, 'parent' => 10 ) ); $display_terms = array(); foreach($all_terms as $term) { // 仅保留不在排除列表中的分类 if(!in_array($term->slug, $exclude_slugs)) { $display_terms[] = $term; } } // 遍历输出分类 $cats = ''; foreach($display_terms as $term) { $cats .= $term->name . ', '; } echo rtrim($cats, ', ');
以上方案中,新增分类只要slug/ID不在排除列表内,就会自动被纳入显示范围,无需修改代码。
内容的提问来源于stack exchange,提问作者Avik Banerjee
相关产品推荐
相关产品推荐

