网站优化

网站优化

Products

当前位置:首页 > 网站优化 >

WordPress中具有相同WP_Query的多个循环

GG网络技术分享 2025-03-18 16:12 3


问题描述:

I have two loops with one same WP_Query, I tried place wp_reset_postdata(); either right after endwhile; in each loop, or just once after all loops (like below), both seems to be working.

What is the correct way of doing it, and why?

<?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?

?>

网友观点:

When WP_Query::have_posts() is called and it determines that there are no more posts, it automatically rewinds that query\'s result pointer to start over from the beginning. You can see the relevant code here, partially reproduced here:

} 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();

}

From the example code in the documentation, it seems that wp_reset_postdata() may only need to be called when you are dealing with multiple querys, but I don\'t know enough about WordPress to be definitive about that.

标签:

提交需求或反馈

Demand feedback