8

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?

2 Answers 2

5

According to the Theme Guide, full loops should be used, even on single templates.

Full loops must be used in all templates. Just calling the_post() in a template like single.php or page.php is not enough.

So yes, it's a best practice to use full loops.

9

The only potential (edit: functional) issue I see is that the loop_end action won't get called if you don't call have_posts() after the last the_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.

5
  • According to the Theme Guide, full loops should be used, even on single templates. "Full loops must be used in all templates. Just calling the_post() in a template like single.php or page.php is not enough." So yes, it's a best practice to use full loops. Feb 17, 2013 at 16:56
  • you should probably add that as an answer. it's necessary if you want your theme accepted and distributed on WP.com or org.
    – Milo
    Feb 17, 2013 at 17:06
  • Alrighty, thanks. I will. I thought you covered it with your answer, so I thought I'd just supplement it with that tidbit. I had never thought about the loop_end action point that you brought up. Good call there. Feb 17, 2013 at 17:48
  • Good question, I unsersrand that accordig to the documentry, the loop is a must in all template files, but I I think both answers don't explain WHY. Specifically why it's necessary to run the_post() inside page.php as this file is not supposed to display any post at all !
    – GyRo
    Oct 31, 2018 at 12:55
  • 1
    @GyRo a page is a type of post. It’s necessary because it sets up data that template tags need to function properly.
    – Milo
    Oct 31, 2018 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.