帮助简化 WordPress 中的 if while 列表循环
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
....
<?php endwhile; endif; ?>
可以很好地理解上面的代码。
1、我可以删除if和while条件吗?直接使用 。
2,我觉得 if (have_posts())
和 while (have_posts())
是一样的。这是多余的吗?
<?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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
#1:不循环调用
the_post
只会让您显示单个帖子。这在单帖子页面上可能是理想的,例如,while
循环经常被省略:#2:你是对的 - 你发布的代码片段在它是
if
和while
的组合。然而,在大多数主题中,用法如下:
在本例中使用
if
语句允许您在根本没有帖子的情况下显示某些内容。如果我们只在该代码中使用 while 循环,则没有任何帖子的页面将不会输出任何内容。#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 thewhile
loop is often omitted:#2: You're correct — the snippet you posted is redundant in its combination of
if
andwhile
.In most themes, however, this is the usage:
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 thewhile
loop in that code, pages without any posts would output nothing.while(have_postS())
将自动按照if(have_postS())
计算have_postS()
,但只要它存在,它就会继续
true
(因为它是一个循环),如果你必须循环并且有某种终止循环的机制,那么使用while
else
一次
if
将做得更好。while(have_postS())
will automatically evaluatehave_postS()
as byif(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 usewhile
else
for once
if
will do better.我不了解 Wordpress,但从它的外观来看, has_posts() 返回一个 true 或 falsy 值。 while 循环仅在传递真值作为条件时才执行,所以是的,您可以将其减少到 3 行:
编辑:将此作为另一个例子来说明为什么复制粘贴代码很糟糕...
I don't know Wordpress, but by the looks of it, has_posts() returns either a truthy or falsy value. The
while
loop only executes if a truthy value is passed as the condition, so yes, you can reduce it to a whoopin 3 lines:Edit: Put this as yet another example as to why copy-pasting code is bad...