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

WordPress如何移除父分类仅保留子分类及对应文章标题

问题原因

你添加'parent'=>0没有达到预期效果,是因为WordPress分类查询的parent参数作用是筛选「父分类ID等于指定值」的分类,填0代表只返回顶级父分类,刚好和你要隐藏父分类、只展示子分类的需求相反。
另外你原有代码里get_categories的参数数组多了一个多余的单引号,属于语法错误,下面的修正代码已经同步处理了这个问题。

解决方案

方案1:循环内过滤(改动最小,兼容性最高)

只需要在遍历分类的循环开头加一行判断,遇到顶级父分类直接跳过即可,不需要修改其他逻辑:

foreach($categories as $category) { 
    // 新增这行:如果是顶级父分类就跳过不处理
    if ($category->parent == 0) continue;
    // 原有逻辑不变

方案2:查询时直接过滤(性能更好)

修改分类查询参数,查询阶段就只返回非顶级的子分类,不需要后续循环判断,适合分类数量较多的场景:
把原有get_categories部分替换为以下代码:

$categories = get_terms( array(
    'taxonomy' => 'category',
    'hide_empty' => true,
    // 排除所有顶级分类
    'parent__not_in' => array(0),
) );
完整修正代码示例
<?php       
// 这里用方案2的查询逻辑,你也可以换成方案1自行调整
$categories = get_terms( 
    array(
        'taxonomy' => 'category',
        'hide_empty' => true,
        'parent__not_in' => array(0),
    ) 
);
foreach($categories as $category) { 
    $args=array(
        'cat' => $category->term_id,
        'post_type' => 'ourservices',
        'orderby' => 'name',
        'order' => 'ASC',
    );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
?>
        <h2 class><?php echo $category->name; ?></h2>
        <ul class="list-group list-group-flush">
        <?php while ( $the_query->have_posts() ) { $the_query->the_post(); ?>
            <li class="list-group-item"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
        <?php }?>
        </ul><br>
<?php } 
} 
wp_reset_postdata();
?>

预期效果参考:
效果示例图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:54:03