Why is while() used instead of say if() here:

        <?php while ( have_posts() ) : the_post(); ?>

        <?php get_template_part( 'content', 'single' ); ?>

        <?php _s_post_nav(); ?>

        <?php
            // If comments are open or we have at least one comment, load up the comment template
            if ( comments_open() || '0' != get_comments_number() ) :
                comments_template();
            endif;
        ?>

    <?php endwhile; // end of the loop. ?>

So I’ve seen this since forever and I’ve used it too because it’s what WordPress uses by default. However today I’m feeling a bit more curious than usual – why is while used instead of if ? Am I expecting to receive more than a single post in single post view ?

https://github.com/Automattic/_s/blob/master/page.php#L18
https://github.com/Automattic/_s/blob/master/single.php#L13

2 Answers
2

As the WordPress Codex for have_posts points out:

As a side effect, have_posts starts, steps through, or resets The Loop. At the end of the loop, have_posts returns 0 after calling rewind_posts.

Looking at the source as it stands today: along with calling rewind_posts() it also fires the loop_end action (which plugins may rely upon) as well as set a flag so in_the_loop() correctly returns false afterwards.

So calling have_posts() on each iteration does more than just return a Boolean. I wouldn’t lean too much on the specifics of the source because that’s a moving object. It’s enough to understand that there are other housekeeping tasks performed when you call have_posts() until it returns false and you’re less likely to introduce subtle interoperability issues if you use it that way even when there is only a single post involved.

Leave a Reply

Your email address will not be published. Required fields are marked *