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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:27:01