WordPress如何用WP Query实现不同文章类型的父子层级页面展示
实现方案
你需要的层级输出完全可以实现,核心思路是先把WP_Query查询到的结果按父级ID分组,再分层输出即可,同时支持自定义文章类型、分页限制。
完整实现代码
<?php // 基础配置 $post_type = 'page'; // 此处修改为对应自定义文章类型的别名,多类型可传数组如 ['page', 'product', 'news'] $posts_per_page = 20; // 每页展示的文章总数 $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; // 查询参数 $args = array( 'post_type' => $post_type, 'orderby' => 'title', 'post_status' => 'publish', 'order' => 'ASC', 'posts_per_page' => $posts_per_page, 'paged' => $paged, // 分页参数 ); $result = new WP_Query( $args ); // 将查询结果按父级ID分组 $posts_by_parent = []; if ( $result->have_posts() ) { foreach ( $result->posts as $p ) { $posts_by_parent[ $p->post_parent ][] = $p; } } ?> <section> <h2><?php echo esc_html( $post_type ); ?></h2> <ul class="post-hierarchy"> <?php // 遍历输出所有顶级父页面(post_parent为0的内容) foreach ( $posts_by_parent[0] as $parent_post ) : setup_postdata( $parent_post ); ?> <li class="parent-item"> <a href="<?php echo esc_url( get_permalink( $parent_post->ID ) ); ?>"> <?php echo get_the_title( $parent_post->ID ); ?> </a> <?php // 存在子页面则输出子层级 if ( isset( $posts_by_parent[ $parent_post->ID ] ) ) : ?> <ul class="child-items"> <?php foreach ( $posts_by_parent[ $parent_post->ID ] as $child_post ) : setup_postdata( $child_post ); ?> <li class="child-item"> <a href="<?php echo esc_url( get_permalink( $child_post->ID ) ); ?>"> <?php echo get_the_title( $child_post->ID ); ?> </a> </li> <?php endforeach; ?> </ul> <?php endif; ?> </li> <?php endforeach; wp_reset_postdata(); ?> </ul> <!-- 可选:分页导航,可根据需求调整样式 --> <div class="pagination"> <?php echo paginate_links( array( 'total' => $result->max_num_pages, 'current' => $paged, ) ); ?> </div> </section>
关键说明
- 如需支持三级及以上的层级展示,只需要在子页面输出位置再加一层子级判断即可
- 若坚持使用
wp_list_pages实现,只需添加post_type参数指定自定义文章类型即可,但该函数默认调取全量符合条件的内容,不支持分页,仅适合小数据量的全量展示场景
内容的提问来源于stack exchange,提问作者Vit
相关产品推荐
相关产品推荐

