rewind_posts()
云策文档标注
概述
rewind_posts() 函数用于重置 WordPress 主查询循环的帖子索引,使其可以重新遍历帖子。它通过调用全局 $wp_query 对象的 rewind_posts() 方法实现。
关键要点
- rewind_posts() 是一个全局函数,用于重置主查询循环的帖子索引。
- 它依赖于全局 $wp_query 对象,如果 $wp_query 未设置则函数直接返回。
- 函数内部调用 $wp_query->rewind_posts() 来执行重置操作。
- 此函数自 WordPress 1.5.0 版本引入。
代码示例
// 主循环
if ( have_posts() ) : while ( have_posts() ) : the_post();
// 循环内容
endwhile; endif;
// 重置循环
rewind_posts();
// 新循环
if ( have_posts() ) : while ( have_posts() ) : the_post();
// 循环内容
endwhile; endif;注意事项
- rewind_posts() 仅适用于主查询循环,对于自定义 WP_Query 对象,应使用 $my_query->rewind_posts() 方法。
- 在重置循环后,可以重新使用 have_posts() 和 the_post() 来遍历帖子。
原文内容
Rewind the loop posts.
Source
function rewind_posts() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
return;
}
$wp_query->rewind_posts();
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 3 content
Codex
Basic Example
// main loop // rewind // new loopSkip to note 4 content
leogermani
Example with custom query migrated from Codex
-1 ); $my_posts = new WP_Query($args); if ($my_posts->have_posts()) : while ($my_posts->have_posts()) : $my_posts->the_post(); ?> // rewind rewind_posts(); ?> // new loop have_posts()) : $my_posts->the_post(); ?>