<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
....
<?php endwhile; endif; ?>
could understand the code on the above well.
1, could i delete the if and while condition? using <?php the_post();?>
directly.
2, i feel the if (have_posts())
is the same as the while (have_posts())
.is it redundance?
#1: Calling
the_post
without a loop will only let you display a single post. This could be desirable on single-post pages, for example, where thewhile
loop is often omitted:#2: You’re correct â the snippet you posted is redundant in its combination of
if
andwhile
.In most themes, however, this is the usage:
The use of the
if
statement in this case allows you to display something if there are no posts at all. If we were to just use thewhile
loop in that code, pages without any posts would output nothing.while(have_postS())
will automatically evaluatehave_postS()
as byif(have_postS())
but it will continue as long as it is
true
(since it is a loop), if you have to loop and some mechanism that terminates loop, then usewhile
else
for once
if
will do better.I don’t know WordPress, but by the looks of it, has_posts() returns either a truthy or falsy value. The
while
loop only executes if a truthy value is passed as the condition, so yes, you can reduce it to a whoopin 3 lines:Edit: Put this as yet another example as to why copy-pasting code is bad…