我测试了一些简单的代码,但结果太奇怪了。
Test 1:
$featured_posts = new WP_Query( $query_args );
while ($featured_posts->have_posts()) {
$featured_posts->the_post();
the_title(); echo \'<br>\';
}
echo \'End: "\' . $featured_posts->have_posts() . \'"\'; // have_post() is TRUE, WHY?
Test 2:
$featured_posts = new WP_Query( $query_args );
$have_posts = $featured_posts->have_posts();
while ($have_posts) {
$featured_posts->the_post();
the_title(); echo \'<br>\';
$have_posts = $featured_posts->have_posts();
}
echo \'End: "\' . $have_posts . \'"\'; // false -> I think false is right.
echo \'End: "\' . $featured_posts->have_posts() . \'"\'; // but still TRUE, WHY?
我遗漏了什么吗?
最合适的回答,由SO网友:Milo 整理而成
如果我们看have_posts()
in source, 我们可以看到为什么会发生这种情况:
function have_posts() {
if ( $this->current_post + 1 < $this->post_count ) {
return true;
} elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
do_action_ref_array(\'loop_end\', array(&$this));
// Do some cleaning up after the loop
$this->rewind_posts();
}
$this->in_the_loop = false;
return false;
}
当它到达循环的末尾时,它调用
rewind_posts
, 重置
current_post
返回到
-1
, 所以下一个电话
have_posts
将再次返回true。
function rewind_posts() {
$this->current_post = -1;
if ( $this->post_count > 0 ) {
$this->post = $this->posts[0];
}
}