Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i need a wp loop in single.php

In WordPress theme development we can use single.php to show the specific single post.

For this purpose the common practice is:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
  <?php the_content();?>
<?php endwhile; ?>
<?php endif; ?>   

Why do I need looping to show a single post? Can any one give some valid reason?

like image 592
himadri Avatar asked Jan 21 '14 05:01

himadri


1 Answers

this was something that killed me for years and I found the answer: No, you don't need to use the LOOP in single pages, you just call the_post() and you have all data needed

.... BUT ....

If you don't use the loop (while(have_posts())....) a hook "loop_end" is not called and if a plugin/process has any action on this hook, it won't work. So for safety reasons you should use the loop.

Also, people ask do I need to check for existence before the loop: if(have_posts())?

<?
if( have_posts() ):
    while( have_posts() ):
        the_post();
        .....
    endwhile;
endif
?>

No, you don't need to check

.... BUT ....

Checking allows you to include headers/titles before the loop and not having them if the loop is empty.

like image 111
paulgagu Avatar answered Oct 12 '22 11:10

paulgagu