Simplify if in a list loop in wordpress

<?php if (have_posts()) : while (have_posts()) : the_post(); ?> .... <?php endwhile; endif; ?> 

could understand the code on the above well.

1, is it possible to remove the if and while condition? using <?php the_post();?> .

2, I feel that if (have_posts()) same as while (have_posts()) . Is it its redundancy?

+6
source share
3 answers

# 1 : calling the_post without a loop will allow you to display only one message. This may be desirable on single-mail pages, for example, where the while 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 right - the fragment you posted is redundant in the combination of if and while .

In most topics this usage is:

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

Using an if in this case allows you to display something if there are no messages at all. If we simply used the while in this code, pages without any messages would not produce anything.

+3
source

while(have_postS()) will automatically evaluate have_postS() as if(have_postS())

but it will continue until it is true (since it is a loop), if you need to execute a loop and some mechanism that completes the loop, then use while

yet

at one time if would be better.

+1
source

I do not know Wordpress, but in appearance has_posts () returns either a true or false value. The while is executed only if the true value is passed as a condition, so yes, you can reduce it to three lines:

 <?php while (have_posts()) : the_post(); ?> .... <?php endwhile;?> 

Edit: put this as another example of why copy code is pasting poorly ...

+1
source

Source: https://habr.com/ru/post/886450/


All Articles