php - 帮助简化 if while 列表在 wordpress 中的循环

标签 php wordpress

<?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:您是对的 - 您发布的代码段在 ifwhile 的组合中是多余的。

然而,在大多数主题中,这是用法:

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

相关文章:

php - MySQL SUM 同一行中的多列

php - 不要在 WooCommerce 中显示通知的 Web 服务失败响应中保存订单

wordpress - 使用 Elementor,如何将文本环绕其他元素?

php - Bootstrap 轮播指示器未在 Wordpress 中显示

php - 使用 wordpress $wpdb 在 <table> 中显示数据库中的数据

wordpress - 联系表格7在“谢谢”页面中重定向通过帖子ID或URL跟踪目标

php - 将一个图像放在另一个图像上

php - 在 Silex 应用程序中共享第 3 方依赖项的最佳实践?

php - PDO 查询不返回行

php - 这个代码是什么意思...?