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

WordPress自定义双WP_Query查询else分支循环不生效问题求解

问题原因

第二个查询的参数本身不存在配置错误,无法生效的核心原因是查询执行后的逻辑缺失:

  • 匹配到days类型文章后没有执行the_post()方法初始化全局$post对象,你引入的partials/days模板内调用的WordPress文章输出函数默认读取全局$post数据,未赋值就会出现无内容输出的情况
  • 两次自定义查询结束后都没有调用wp_reset_postdata()重置主查询数据,会干扰当前页面后续其他查询的正常输出

修正后完整代码

<?php
$first_args = array( 
    'post_type' => 'timeline', 
    'posts_per_page' => 1,
    'tax_query' => array(
        array (
            'taxonomy' => 'pin',
            'field' => 'slug',
            'terms' => 'pin-post-to-homepage',
        )
    ),
);  

$second_args = array( 
    'post_type' => 'days',
    'posts_per_page' => 1,
    'orderby' => 'rand'
);      

$first_query = new WP_Query($first_args);
if ($first_query->have_posts()) {
    while ( $first_query->have_posts() ) {
        $first_query->the_post();
        get_template_part('partials/andSoOnTimeline');
    }
    wp_reset_postdata();
} else {
    $second_query = new WP_Query($second_args);
    if ($second_query->have_posts() ){
        while ( $second_query->have_posts() ) {
            $second_query->the_post();
            get_template_part('partials/days');
        }
        wp_reset_postdata();
    }
}
?>

如果修改后仍然无内容输出,可以在第二个查询的if ($second_query->have_posts())判断前加入var_dump($second_query->posts)验证是否真的查询到了days类型的文章,排除后台无对应文章的问题。

内容的提问来源于stack exchange,提问作者R-G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:15:01