1
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

4

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.

2

You're right, it's not necessary.

However, you'll often want to wrap your post-output in a <div class="posts"> or something similar, and you can make outputting that div conditional based on whether there will actually be anything in it, which makes it much cleaner to style in my opinion, because you won't end up with <div class="posts"></div> if there are no posts. You won't need to use any :empty selectors in your CSS to hide this empty div, since it won't be in the DOM at all.

Your Answer

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

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