WordPress如何对自定义文章类型leistungen执行嵌套/多级查询
问题排查
- 外层查询参数变量名不匹配:定义了
$outer_args但实例化WP_Query时传入了未定义的$args,导致外层查询无返回结果。 - 内层查询对象名错误:实例化的内层查询对象为
$issue,后续循环调用的是未定义的$inner_query,内层逻辑完全无法执行。 - 输出结构不符合需求:子模块使用
<p>标签,未按要求输出无序列表结构。 - 查询重置方法不规范:自定义
WP_Query查询后使用wp_reset_postdata()即可,wp_reset_query()是针对主查询的重置方法,无需使用。
修正后的嵌套查询代码
<?php // 查询所有父级服务 $outer_args = [ 'post_type' => 'leistungen', 'posts_per_page' => -1, 'post_parent' => 0, 'post_status' => 'publish' ]; $outer_query = new WP_Query($outer_args); if ($outer_query->have_posts()) : while ($outer_query->have_posts()) : $outer_query->the_post(); $parent_id = get_the_ID(); ?> <!-- 父服务标题,若需要<strong>标签可替换h2标签 --> <h2><?php the_title(); ?></h2> <?php // 查询当前父服务下的所有子模块 $inner_query = new WP_Query([ 'post_type' => 'leistungen', 'posts_per_page' => -1, 'post_parent' => $parent_id, 'post_status' => 'publish' ]); if ($inner_query->have_posts()) : ?> <ul> <?php while ($inner_query->have_posts()) : $inner_query->the_post(); ?> <li><?php the_title(); ?></li> <?php endwhile; ?> </ul> <?php endif; // 重置内层查询数据 wp_reset_postdata(); endwhile; endif; // 重置外层查询数据 wp_reset_postdata(); ?>
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

