<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
....
<?php endwhile; endif; ?>
Run Code Online (Sandbox Code Playgroud)
能够理解上面的代码.
1,我可以删除if和while条件吗?<?php the_post();?>
直接使用.
2,我觉得和if (have_posts())
它一样是while (have_posts())
冗余的吗?
#1:the_post
不循环调用只会让您显示单个帖子。这在单帖子页面上可能是理想的,例如,循环while
经常被省略:
<?php\n// single.php\nif ( have_posts() ):\n the_post();\n?>\n<p><?php the_content(); ?></p>\n<? else: ?>\n<p>No post found.</p>\n<? endif ?>\n
Run Code Online (Sandbox Code Playgroud)\n\n#2:你是对的 \xe2\x80\x94 你发布的代码片段在if
和的组合中是多余的while
。
然而,在大多数主题中,用法如下:
\n\n<?php\nif ( have_posts() ):\n while ( have_posts() ): the_post();\n?>\n<div class="post"><?php the_content(); ?></div>\n<?php endwhile; else: ?>\n<p>No posts found.</p>\n<?php endif; ?>\n
Run Code Online (Sandbox Code Playgroud)\n\n在这种情况下使用该if
语句可以让您在根本没有帖子的情况下显示一些内容。如果我们只while
在该代码中使用循环,则没有任何帖子的页面将不会输出任何内容。