WordPress循环未遵循参数设置问题求助
WordPress循环参数失效问题解决
你的代码里有几个问题导致参数被忽略,页面混在文章里显示:
- 无效参数混淆:
numberposts是get_posts()的专用参数,WP_Query不识别它,虽然你写了posts_per_page,但保留无效参数可能干扰查询逻辑,直接删掉numberposts即可。 - wp_reset_postdata()位置错误:这个函数是用来恢复全局
$post变量的,应该放在循环结束之后,你现在放在查询前完全起不到作用。 - orderby参数的潜在问题:用
menu_order排序时,文章默认的menu_order值是0,如果你的页面也设置了相同的menu_order,再加上有其他钩子修改查询,就可能被误查出来。如果不需要按菜单顺序排序,可以改成date或者其他合适的排序方式;如果必须用menu_order,确保只有文章设置了这个值。 - 缺少post_status参数:显式指定
post_status' => 'publish',确保只调取已发布的文章,避免意外包含其他状态的内容。
修正后的代码:
<h1 id="" class="offset"><?php _e('Aktuell','Main'); ?></h1> <?php // WP_Query arguments $args = array ( 'post_type' => 'post', 'cat' => '50,47', 'posts_per_page' => 3, // 不用加引号,数字类型更稳妥 'ignore_sticky_posts' => true, 'order' => 'ASC', 'orderby' => 'menu_order', // 如果不需要可改成'date' 'post_status' => 'publish' ); // The Query $query = new WP_Query( $args ); // The Loop if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); ?> <article <?php post_class(); ?>> <!-- 这里添加文章内容输出,比如标题、摘要等 --> <h2><?php the_title(); ?></h2> <?php the_excerpt(); ?> </article> <?php } // 恢复原始文章数据,放在循环结束后 wp_reset_postdata(); } else { // no posts found echo '<p>暂无文章</p>'; } ?> </div>
另外,如果修正后还是有页面显示,检查你的主题或插件是否有pre_get_posts钩子修改了查询规则,这个钩子经常会全局改变WP_Query的参数,导致自定义查询被干扰。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

