我正在研究 wordpress query_posts。我想在索引页上显示 12 个帖子,连续 3 个项目。所以我想在每一行的第一项上都有一个“clear:both”css。请问我该怎么做?
<?php query_posts(array('showposts' => 9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?> <div> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div> <!-- clear class on each 4th item --> <h2><?php the_title(); ?></h2> <?php the_content(); ?> </div> <?php endif; ?> </div> <?php wp_reset_query(); ?>
最佳答案
<?php query_posts(array('showposts' => 9, 'post_parent' => $post->ID, 'post_type' => 'page', 'order' => 'ASC')); ?>
<div>
<?php $i = 0; $attr = " class='clear_float'"; ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div<?php if(($i++)%3 == 0) {echo $attr;} ?>> <!-- clear class on each 4th item -->
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
<?php endif; ?>
</div>
<?php wp_reset_query(); ?>
我添加了 2 行。
<?php $i = 0; $attr = " class='clear_float'"; ?>
和
<div<?php if(($i++)%3 == 0) {echo $attr;} ?>> <!-- clear class on each 4th item -->
=====更新=====
要添加第 3 个项目类,我建议将类添加到所有项目,以实现简单性和更好的控制
为此,在循环之前:
$i = 0;
在div
里面在循环中:
<div class="item-<?php echo (($i++) % 3) + 1 ?>">
因此,对于每一行,第一项的类 = item-1
,第三项的类别 = item-3
关于php - 简单的php计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3762233/