A Proper Loop

Working on _s, I came across an issue asking if we could remove the loop syntax in singular templates since there is never more than one post. I asked for Michael Field‘s opinion on the matter and he pointed me to a core ticket for Twenty Eleven about the same issue.

    while ( have_posts() ) :
    // Code here...
<?php endwhile; ?>

When have_posts() is called for the first time, it will return true and we can go about our business of calling the_post() and displaying the content. One of the things the_post() does, is to set the internal in_the_loop property to true, signalling – you guessed it – that we are in the loop. In the second iteration of the while loop, there is no post and have_posts() sets in_the_loop back to false.

This is important! It makes the in_the_loop() (#) conditional tag work, that plugins might rely on to properly work. If we would not call have_posts(), WP_Query‘s in_the_loop attribute would stay true for the rest of the page load, possibly causing havoc in widgets or other parts of the page.

Author: Konstantin Obenland

Release Lead (Ret.) at Automattic, WordPress Contributor. Can be found on Twitter (@obenland).