[英]Wordpress looping through posts
我想知道是否有人可以解释以下内容,我正在关注wordpress的教程,我看到这个代码用于遍历帖子并显示它们,但是我有点困惑,因为这里实际发生了什么。
<?php
if( have_posts() ):
while( have_posts() ): the_post(); ?>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
<?php endwhile;
endif;
?>
关注我的while( have_posts() ): the_post(); ?>
部分是while( have_posts() ): the_post(); ?>
while( have_posts() ): the_post(); ?>
首先,这里的语法不是我以前见过的,你有while循环括号打开和关闭然后你有: the post()
这是第二部分是什么? 我虽然while循环的条件需要在while()
。 这是什么: the_post()
它做了什么?
另外,方法have_posts()
如果有帖子则返回true,我不明白为什么这不是一个无限循环,因为只要数据库中至少有一个帖子, have_posts()
肯定会一直为真。
最后,我喜欢使用PHP短标签,现在当我这样做时,这段代码不再有效,这是我的这个代码的版本有短标签,有人可以告诉我我哪里出错了。
<? if ( have_posts() ): ?>
<? while ( have_posts() ) : the_post(): ?>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
<? endwhile; ?>
<? endif; ?>
PHP风暴突出了最后一个:
在<? while ( have_posts() ) : the_post(): ?> as the error, but if I change it to a
<? while ( have_posts() ) : the_post(): ?> as the error, but if I change it to a
;`我得到以下错误
Warning: count(): Parameter must be an array or an object that implements Countable in C:\\laragon\\www\\blog\\wp-includes\\post-template.php on line 293
我知道这里有几个问题,我道歉,我只是想完全了解这里发生的事情,而不仅仅是盲目地复制和粘贴。 希望你能理解。
提前致谢。
1)循环语法
正在使用的语法是在PHP中执行“控制结构”的另一种方法,如下所述: https : //www.php.net/manual/en/control-structures.alternative-syntax.php
从本质上讲,它是编写以下内容的另一种方式:
while (have_posts()) {
the_post();
?>
<h3><?php the_title(); ?></h3>
<p><?php the_content(); ?></p>
<?php
}
代码的功能没有区别,只是有时比使用花括号更容易匹配
2. have_posts()
和the_post()
你是对的,如果有帖子,这将返回true,但是调用the_post()
函数会阻止它无限循环。 the_post()
将做的是设置访问帖子数据所需的所有变量(例如$post
全局变量),然后它会将计数器增加1.这意味着,如果你只有一个帖子,是第二次调用have_posts
现在将返回false,因为计数器等于它可用的帖子数。
3. PHP短标签
我猜这是因为你的服务器没有设置为使用短标签。 您需要在php.ini配置中启用short_open_tag
设置。 https://www.php.net/manual/en/ini.core.php#ini.short-open-tag
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.