Why we use if with while loop?

if(have_posts()):
    while(have_posts()):
        the_post();
        the_content();
    endwhile;
endif;

Without if condition this below code also works fine:

while(have_posts()):
    the_post();
    the_content();
endwhile;

Thanks.

2 Answers
2

You only need the if ( have_posts() ) : if, as the name of the function suggets, you need to do something different if you don’t have posts. This would be something like displaying a “No posts found.” message.

But you’d only need that on templates that could show no posts, like archives and search. For single post and page templates the if is unnecessary.

Leave a Comment