全球的rewind_posts
File: wp-includes/query.php
784: /**
785: * Rewind the loop posts.
786: *
787: * @since 1.5.0
788: *
789: * @global WP_Query $wp_query Global WP_Query instance.
790: */
791: function rewind_posts() {
792: global $wp_query;
793: $wp_query->rewind_posts();
794: }
以及
rewind_posts
从…起
WP_Query
班
File: wp-includes/class-wp-query.php
3144: * Rewind the posts and reset post index.
3145: *
3146: * @since 1.5.0
3147: * @access public
3148: */
3149: public function rewind_posts() {
3150: $this->current_post = -1;
3151: if ( $this->post_count > 0 ) {
3152: $this->post = $this->posts[0];
3153: }
3154: }
可以帮助我们了解
$wp_query
使用全局
rewind_posts
.
codex 您设置的指针:
// main loop
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; endif; ?>
// rewind
<?php rewind_posts(); ?>
// new loop
<?php while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
表明这与
$the_post
方法
那么,什么是the_post()
?
File: /class-wp-query.php
3095: public function the_post() {
3096: global $post;
3097: $this->in_the_loop = true;
3098:
3099: if ( $this->current_post == -1 ) // loop has just started
3100: /**
3101: * Fires once the loop is started.
3102: *
3103: * @since 2.0.0
3104: *
3105: * @param WP_Query &$this The WP_Query instance (passed by reference).
3106: */
3107: do_action_ref_array( \'loop_start\', array( &$this ) );
3108:
3109: $post = $this->next_post();
3110: $this->setup_postdata( $post );
3111: }
至少我们可以理解
global $post
每次迭代
while
环
理解的关键是next_post()
方法
File: wp-includes/class-wp-query.php
3068: /**
3069: * Set up the next post and iterate current post index.
3070: *
3071: * @since 1.5.0
3072: * @access public
3073: *
3074: * @return WP_Post Next post.
3075: */
3076: public function next_post() {
3077:
3078: $this->current_post++;
3079:
3080: $this->post = $this->posts[$this->current_post];
3081: return $this->post;
3082: }
该方法最终解释了我们增加当前post指针的原因:
$this->current_post++;
请注意,在整个变量上方的表达式中
$this->current_post
将递增。
($this->current_post)++;
这相当于:
$this->current_post = $this->current_post + 1;
对于那些讨厌承认语法的人
$this->current_post++;
增加变量非常酷。
回顾一下:
自从我们打电话以来the_post()
并增加了$this->current_post
指针如果我们计划再次循环,现在需要将该指针设置为-1。
3149: public function rewind_posts() {
3150: $this->current_post = -1;
3151: if ( $this->post_count > 0 ) {
3152: $this->post = $this->posts[0];
3153: }
3154: }
虽然很奇怪,但它确实有效。