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

如何在WordPress中显示父分类下的子分类名称及对应文章

实现指定父分类下子分类及对应3篇文章的方法

嘿,作为WordPress新手,这个需求其实很好实现,咱们直接上可落地的实操方案,每一步都给你讲明白:

第一步:确定你的父分类ID

先打开WordPress后台,进入「文章」→「分类」,点击你要指定的父分类(比如“父分类1”),此时浏览器地址栏里会有类似 ...wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=5&post_type=post 的链接,这里的tag_ID=5里的5就是你的父分类ID,记下来,后面要用到。

第二步:添加自定义代码到主题模板

你可以把下面的代码放到主题的category.php(分类页面)、page.php(自定义页面)或者sidebar.php(侧边栏)里,根据你想展示的位置来选:

<?php
// 替换成你的父分类ID
$parent_cat_id = 5;

// 获取该父分类下的所有子分类
$child_categories = get_categories(array(
    'parent' => $parent_cat_id,
    'hide_empty' => false, // 即使子分类无文章也显示,想隐藏的话改成true
    'orderby' => 'name',
    'order' => 'ASC'
));

// 循环每个子分类
foreach ($child_categories as $child_cat) {
    // 输出子分类名称
    echo '<h3>' . $child_cat->name . '</h3>';
    echo '<ul>';

    // 查询该子分类下的3篇文章
    $args = array(
        'cat' => $child_cat->term_id,
        'posts_per_page' => 3,
        'post_status' => 'publish',
        'orderby' => 'date',
        'order' => 'DESC'
    );
    $child_posts = new WP_Query($args);

    // 循环输出文章
    if ($child_posts->have_posts()) {
        while ($child_posts->have_posts()) {
            $child_posts->the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
    } else {
        // 如果子分类下无文章,显示提示
        echo '<li>暂无文章</li>';
    }

    echo '</ul>';

    // 重置查询,避免影响后续内容
    wp_reset_postdata();
}
?>

代码细节调整说明

  • $parent_cat_id = 5;:一定要把5替换成你刚才找到的父分类ID,这是核心配置项
  • hide_empty:设置为false会显示所有子分类(哪怕没文章),如果只想展示有文章的子分类,改成true就行
  • posts_per_page => 3:控制每个子分类下显示的文章数量,这里是3,你可以按需修改成其他数字
  • 如果你想显示文章摘要而不只是标题,可以把<li>里的内容改成:
    <li>
        <a href="' . get_permalink() . '">' . get_the_title() . '</a>
        <p>' . get_the_excerpt() . '</p>
    </li>
    

设置好之后,访问对应的页面就能看到指定父分类下的所有子分类,每个子分类下面跟着3篇最新文章啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:21:54