[英]Multiple loops with same WP_Query in WordPress
我有一个相同的WP_Query有两个循环,我尝试放置wp_reset_postdata();
无论是右后endwhile;
在每个循环中,或者在所有循环中都只有一次(如下所示),两者似乎都在工作。
正确的做法是什么,为什么?
<?php
$q = new WP_Query((array(
'cat' => 1,
'posts_per_page' => -1
)));
if ($q->have_posts()) :
while ($q->have_posts()) : $q->the_post();
// first loop
endwhile;
endif;
if ($q->have_posts()) :
while ($q->have_posts()) : $q->the_post();
// second loop
endwhile;
endif;
wp_reset_postdata(); // should reset be here or after endwhile; in each loop?
?>
当WP_Query::have_posts()
并确定没有更多的帖子时,它将自动倒回该查询的结果指针以从头开始。 您可以在此处查看相关代码, 在此处部分复制:
} elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
/* Some code removed here for the sake of brevity */
// Do some cleaning up after the loop
$this->rewind_posts();
}
从文档中的示例代码来看,似乎只在处理多个查询时才需要调用wp_reset_postdata()
,但是我对WordPress的了解并不足够。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.