0

Why post loop should be like

<?php if(have_posts())
{
   while(have_posts())
   {
      the_post();
      code for post here
   }
}
?>

this if statement looks so unnecessary, cause while have same statement have_posts return false when dont detect any post and true when detect any post so while doesn't work if there are no posts, so why check it in dive above that while?

1
  • It might not make much sense with this minimal example, because there is nothing else done here, if there weren’t any posts. codex.wordpress.org/The_Loop_in_Action#Begin_The_Loop: “When the posts collection is exhausted (the posts counter matches the total number of posts), the while loop ends and The Loop moves on to whatever instructions it has beyond the while statement, still within the if test. For example, the if might have an else clause with statements to be executed if the posts collection did not contain any data in the first place. Commented Jul 9, 2021 at 9:57

1 Answer 1

1

This is same like you check array/object is empty or not before loop this in core PHP.

It will just check the query you fire has posts available or not. If you directly drive the loop will give error if empty.

Sign up to request clarification or add additional context in comments.

2 Comments

No, looping over an empty array will not throw any errors. Only if the variable in question was not an array to begin with, you would get errors.
And have_posts returns true or false, so the WP code won’t throw an error either without the if.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.