Php 循环运行不正常时内部的迭代

Php 循环运行不正常时内部的迭代,php,wordpress,Php,Wordpress,我正在用$I在WordPress中进行迭代。但第一个项目打印1,其余项目打印3 以下是一个例子: <?php $i = 0; while($posts->have_posts()){ $i++; $posts->the_post(); $html .= '<div class="th-block ' . $i . '">'; $html .= '</div>'; }

我正在用$I在WordPress中进行迭代。但第一个项目打印1,其余项目打印3

以下是一个例子:

<?php
    $i = 0;
    while($posts->have_posts()){
        $i++;
        $posts->the_post();

        $html .= '<div class="th-block ' . $i . '">';
        $html .= '</div>';
    }
    echo $html;
 ?>

但它是这样印刷的

<div class="th-block 1"></div>
<div class="th-block 3"></div>
<div class="th-block 3"></div>
<div class="th-block 3"></div>
....
<div class="th-block 0"></div>
<div class="th-block 1"></div>
<div class="th-block 2"></div>
<div class="th-block 3"></div>

....

我需要在循环中确定一个限制吗?我搜索了stackoverflow,但没有找到任何解决方案。

这似乎是一个很小的问题,请尝试下面的代码,这将对您有用

<?php
    $i = 0;
    while($posts->have_posts()){
        $posts->the_post();

        $html .= '<div class="th-block ' . $i . '">';
        $html .= '</div>';

        $i++;
    }
    echo $html;
 ?>

我没有测试代码。

更改“I”变量的名称。 wordpress有时会使用具有此名称的全局变量


只需将其更改为iiiii jjjjj之类的内容

您好,它非常简单

 <?php
        $i = 0;
        while($posts->have_posts()){
            $posts->the_post();

            $html .= '<div class="th-block ' . $i . '">';
            $html .= '</div>';

            $i++;
        }
        echo $html;
     ?>

您只需在HTML内容之后添加$i++,但现在您的HTML显示如下

<div class="th-block 1"></div>
<div class="th-block 3"></div>
<div class="th-block 3"></div>
<div class="th-block 3"></div>
....
<div class="th-block 0"></div>
<div class="th-block 1"></div>
<div class="th-block 2"></div>
<div class="th-block 3"></div>

如果要从一个用户$i=1开始,而不是从零开始,请参阅:

'">';
$html.='';
$i++;
}
echo$html;
?>

在每个循环上打印$i,看看它给出了什么。是
$posts->have_posts()
还是
$posts->the_post();
以任何方式修改$i?我已经检查了您的脚本,它工作正常。脚本返回如下内容。