WordPress循环浏览帖子

时间:2019-03-24 20:56:33

标签: php wordpress

我想知道是否有人可以解释以下内容,我正在关注有关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循环括号,然后再使用: 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;`我遇到了以下错误

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 个答案:

答案 0 :(得分:0)

1)While循环语法

正在使用的语法是在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

相关问题