I’m writing my first WordPress theme and have a question about the use of The Loop in page templates. The page templates I’ve looked at all follow basically the same pattern (example from Twenty Twelve):
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php comments_template( '', true ); ?>
<?php endwhile; // end of the loop. ?>
But a page will only have one post associated with it so iterating through the posts seems unnecessary. My page template is more readable and seems to work fine:
<?php
the_post();
the_title('<h1>', '</h1>');
the_content();
?>
Is this a good practice? Are there any downsides?
According to the Theme Guide, full loops should be used, even on single templates.
So yes, it’s a best practice to use full loops.
The only potential (edit: functional) issue I see is that the
loop_end
action won’t get called if you don’t callhave_posts()
after the lastthe_post()
, so anything hooked to that action won’t run.In practice, I’ve been doing it that way in bespoke client themes and have never encountered an issue, but it depends on what plugins may be used and whether or not they hook anything on
loop_end
.