<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
....
<?php endwhile; endif; ?>
能很好地理解上面的代码。
1,我可以删除if和while条件吗?使用 <?php the_post();?>
直接。
2,我觉得if (have_posts())
与 while (have_posts())
相同.是冗余吗?
最佳答案
#1:在没有循环的情况下调用 the_post
只会让您显示一个帖子。这在单篇文章页面上可能是可取的,例如,通常省略 while
循环的地方:
<?php
// single.php
if ( have_posts() ):
the_post();
?>
<p><?php the_content(); ?></p>
<? else: ?>
<p>No post found.</p>
<? endif ?>
#2:您是对的 - 您发布的代码段在 if
和 while
的组合中是多余的。
然而,在大多数主题中,这是用法:
<?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; ?>
在这种情况下使用 if
语句允许您在根本没有帖子的情况下显示一些内容。如果我们只在该代码中使用 while
循环,没有任何帖子的页面将不会输出任何内容。
关于php - 帮助简化 if while 列表在 wordpress 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5752515/