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

如何在WordPress自定义文章类型中获取分类及文章标题层级结构

WordPress自定义文章类型层级分类+文章输出方案

以下代码可直接嵌入主题模板文件(如自定义文章类型归档模板、独立页面模板)使用,使用前请替换代码中对应的自定义文章类型、自定义分类法slug为你实际使用的参数。

<?php
// 配置参数:替换为你自己的对应别名
$cpt_slug = 'your_cpt_slug'; // 自定义文章类型别名
$tax_slug = 'your_tax_slug'; // 绑定到该CPT的自定义分类法别名,用默认分类就填category

// 获取所有顶层父分类
$parent_terms = get_terms([
    'taxonomy' => $tax_slug,
    'parent' => 0,
    'hide_empty' => true, // 隐藏无文章的分类,不需要可改为false
]);

if (!empty($parent_terms)) :
    foreach ($parent_terms as $parent_term) :
?>
    <!-- 输出父分类名称 -->
    <h2><?php echo esc_html($parent_term->name); ?></h2>

    <?php
    // 获取当前父分类下的所有子分类
    $child_terms = get_terms([
        'taxonomy' => $tax_slug,
        'parent' => $parent_term->term_id,
        'hide_empty' => true,
    ]);

    if (!empty($child_terms)) :
        foreach ($child_terms as $child_term) :
    ?>
        <!-- 输出子分类名称 -->
        <h3 style="margin-left: 20px;"><?php echo esc_html($child_term->name); ?></h3>

        <?php
        // 查询该子分类下的自定义文章
        $cpt_query = new WP_Query([
            'post_type' => $cpt_slug,
            'posts_per_page' => -1, // 输出所有文章,可自定义数量
            'tax_query' => [
                [
                    'taxonomy' => $tax_slug,
                    'field' => 'term_id',
                    'terms' => $child_term->term_id,
                ]
            ],
            'post_status' => 'publish',
            'orderby' => 'title',
            'order' => 'ASC'
        ]);

        if ($cpt_query->have_posts()) :
        ?>
            <ul style="margin-left: 40px;">
                <?php while ($cpt_query->have_posts()) : $cpt_query->the_post(); ?>
                    <!-- 输出文章标题,需要跳转链接可替换为下方注释的代码 -->
                    <li><?php the_title(); ?></li>
                    <!-- 带链接版本:<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> -->
                <?php endwhile; ?>
            </ul>
        <?php
        endif;
        // 重置查询,避免影响页面其他逻辑
        wp_reset_postdata();
        ?>

    <?php endforeach; endif; ?>

<?php endforeach; endif; ?>

注意事项

  • 代码里的内联margin样式是为了直观展示层级效果,可根据自己的设计需求删除后单独写CSS规则
  • 若你的分类结构支持三级及以上嵌套,可在子分类循环里递归复用查询子分类+文章的逻辑
  • 访问量较高的站点建议给查询结果加缓存,减少数据库请求

内容的提问来源于stack exchange,提问作者Mohammad Kanak Ferdous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:24:03