由于某种原因,我在查询结果的末尾得到了一个额外的<li> </li>
。我该如何防止这种情况发生?
<li>
<?php
$counter = 0;
$query = new WP_Query( array( 'post_type' => 'serivces' ) );
while ( $query->have_posts() ) : $query->the_post(); $counter++;
?>
<div class="col-md-4 wp4">
<h2 class="text-left"><?php the_title(); ?></h2>
<p class="text-left"><?php the_content(); ?></p>
</div>
<?php
if ($counter > 0 && $counter % 3 == 0) {
echo '</li><li>';
}
endwhile;
?>
</li>
您可以删除顶部的<li>
和底部的</li>
,以及循环开始和代码结束时的一些额外if语句,如下所示:
<?php
$counter = 0;
$query = new WP_Query( array( 'post_type' => 'serivces' ) );
while ( $query->have_posts() ) :
$query->the_post();
$counter++;
if($counter % 3 == 1) { echo '<li>'; }
?>
<div class="col-md-4 wp4">
<h2 class="text-left"><?php the_title(); ?></h2>
<p class="text-left"><?php the_content(); ?></p>
</div>
<?php
if ($counter > 0 && $counter % 3 == 0) {
echo '</li>';
}
endwhile;
if($counter % 3 != 0) { echo '</li>'; }
?>
底部的if语句仅在while循环中的最后一个if语句没有出现在3的倍数的迭代中时执行,以确保列表元素始终处于关闭状态。