我需要一个 div 来包装 WordPress 循环中的每四个帖子。所以它会像
<div>
four posts
</div>
<div>
four posts
</div>
我当前的代码是这样的
<?php
$i = 0;
$wrap_div = "<div class='frak'>";
if ( have_posts() ) {
echo $wrap_div;
while ( have_posts() ) {
the_post();
?>
<div class="wine-section">
<?php the_post_thumbnail(); ?>
<div class="wine-info">
<a href="<?php the_permalink(); ?>"><?php the_title( '<h1>', '</h1>' ); ?></a>
<?php the_meta(); ?>
</div><!-- /wine-info -->
<div class="c"></div>
</div><!-- /wine-section -->
<?php
if ($i % 4 == 0) { echo "</div>" . $wrap_div; }
} // end while
} // end if
$i++;
?>
此代码单独包装每个帖子。有任何想法吗?
正如 geomagas 指出的那样 - 您正在循环外部增加变量。然后0 % 4 == 0
确实评估为 true - 这是因为当您将 0 除以 4 时,您会得到 0。为了解决这种情况,您还需要一条规则。
另外不要忘记,使用您当前的代码,如果帖子总数为 12,那么您的帖子末尾将有一个空的“frak”div。
<?php
$i = 0;
$wrap_div = "<div class='frak'>";
if ( have_posts() ) {
// Grab the total posts that are being displayed
$total_posts = $wp_query->post_count;
echo $wrap_div;
while ( have_posts() ) {
the_post(); ?>
<div class="wine-section">
<?php the_post_thumbnail(); ?>
<div class="wine-info">
<a href="<?php the_permalink(); ?>"><?php the_title( '<h1>', '</h1>' ); ?></a>
<?php the_meta(); ?>
</div><!-- /wine-info -->
<div class="c"></div>
</div><!-- /wine-section -->
<?php
// Is this a fourth post? If so, make sure it is not the last post?
if ( $i % 4 == 0 && $i != 0 && ( $i + 1 ) != $total_posts ) {
echo '</div>' . $wrap_div;
}
$i ++;
} // end while
// Close the $wrap_div
echo '</div>';
} // end if
?>
正如你所看到的if
打印结束标记和新换行的语句现在更加复杂。
它确保 $i 不为 0(意味着它仍然是第一个帖子)并且 $i + 1 不等于显示的帖子总数(对于这种情况,我们在while()
loop).
如果您想知道为什么我们要在while()
循环 - 只是因为你的帖子可能并不总是在 4 上完全是多个(我不确定这里的英语翻译是否正确) - 如果是这种情况并且你在 while 循环后没有关闭你的 div - 你就会有麻烦。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)