Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help simplify if while list loop in wordpress

Tags:

php

wordpress

<?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?

like image 313
zhuanzhou Avatar asked Apr 22 '11 05:04

zhuanzhou


2 Answers

#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 the while loop is often omitted:

<?php
// single.php
if ( have_posts() ):
    the_post();
?>
<p><?php the_content(); ?></p>
<? else: ?>
<p>No post found.</p>
<? endif ?>

#2: You're correct — the snippet you posted is redundant in its combination of if and while.

In most themes, however, this is the usage:

<?php
if ( have_posts() ):
    while ( have_posts() ): the_post();
?>
<div class="post"><?php the_content(); ?></div>
<?php endwhile; else: ?>
<p>No posts found.</p>
<?php endif; ?>

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 the while loop in that code, pages without any posts would output nothing.

like image 72
Jon Gauthier Avatar answered Sep 20 '22 05:09

Jon Gauthier


while(have_postS()) will automatically evaluate have_postS() as by if(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 use while

else

for once if will do better.

like image 45
Santosh Linkha Avatar answered Sep 23 '22 05:09

Santosh Linkha