Why i need a wp loop in single.php
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.
The WordPress Loop instantiates some functions like the_title()
, the_content()
and others.
In other words, your post is loaded in that loop, and the loop is gone through once if you are on a single post. Although it might be strange to have a loop, it is actually quite useful.
WordPress uses a template hierarchy, which is a way of choosing which template to load for a given post/page. In your single.php
, the loop will run once. But if you do not have a single.php
file, WordPress will use index.php
instead for that same post.
For the sake of consistency, having a loop which works for any number of posts is helpful. Else, in you index.php
, you would have needed a case for one post and another case for multiple posts and keeping a consistent templating method would be difficult.