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

如何在WordPress中通过函数获取并展示父页面的子页面列表

实现WordPress父页面展示子页面列表

没问题,我来帮你调整这段代码,让它能在每个顶级父页面下方展示对应的子页面列表。核心思路就是在遍历顶级页面的循环里,嵌套一个子查询来获取当前父页面的所有子页面,具体修改如下:

修改后的代码

function getPagesHierarchy() {
    // 查询所有顶级父页面(post_parent=0)
    $pagesQuery = new WP_Query(array(
        'post_type'      => 'page',
        'posts_per_page' => -1,
        'post_parent'    => 0,
        'order'          => 'ASC',
        'post_status'    => 'publish'
    ));

    if ($pagesQuery->have_posts()) {
        // 开始遍历顶级父页面
        while($pagesQuery->have_posts()) {
            $pagesQuery->the_post();
            // 输出父页面标题(改成带链接的形式更实用)
            echo '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
            
            // 查询当前父页面的子页面
            $childPagesQuery = new WP_Query(array(
                'post_type'      => 'page',
                'posts_per_page' => -1,
                'post_parent'    => get_the_ID(), // 用当前父页面ID作为子页面的父ID
                'order'          => 'ASC',
                'post_status'    => 'publish'
            ));

            // 如果有子页面,输出结构化的列表
            if ($childPagesQuery->have_posts()) {
                echo '<ul>';
                while($childPagesQuery->have_posts()) {
                    $childPagesQuery->the_post();
                    echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
                }
                echo '</ul>';
                // 重置子页面查询上下文,避免干扰后续查询
                wp_reset_postdata();
            }
        }
        // 重置顶级页面查询上下文
        wp_reset_postdata();
    }
}

代码说明

  • 外层循环负责拉取所有顶级父页面,同时输出带跳转链接的父页面标题,比单纯的文字展示更符合需求。
  • 内层循环针对每个父页面,通过get_the_ID()获取当前页面ID,以此作为post_parent参数精准查询对应的子页面。
  • 用<ul>和<li>包裹子页面列表,结构更清晰,也方便后续通过CSS美化样式。
  • 每次循环结束后调用wp_reset_postdata(),确保查询上下文不会和其他WordPress查询冲突。

更简洁的备选方案:使用wp_list_pages

如果你不想手动写嵌套查询,WordPress内置的wp_list_pages函数可以一键生成层级页面列表,代码更简洁:

function getPagesHierarchy() {
    echo '<ul>';
    wp_list_pages(array(
        'post_type' => 'page',
        'title_li' => '', // 去掉默认的列表标题
        'depth' => 2, // 只展示顶级页面和一级子页面
        'sort_column' => 'menu_order, post_title' // 可按菜单顺序或标题排序
    ));
    echo '</ul>';
}

这个函数会自动帮你处理层级关系,不需要手动写嵌套循环,非常省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:20:29