循环将.last类添加到循环中的最后一项

时间:2011-06-30 11:56:39

标签: php wordpress

我使用wordpress并使用以下内容获取最近3篇最新帖子:

    <?php query_posts('showposts='.$latest_num.'&cat=-'.$featured_cat.','.$latest_ignore.''); ?>
    <?php while (have_posts()) : the_post(); ?>
    <li>
        <div class="imgholder">
            <a href="/wp-content/themes/twentyten/images/slide1.jpg" data-gal="prettyPhoto[featured]" title="<?php the_title(); ?>">
                <img src="<?php echo get_post_meta($post->ID, 'thumbnail',true) ?>" width="275" height="145" alt="Post Image" class="postimg-s" />
            </a>
        </div>
        <h4><?php the_title(); ?></h4>
        <p><?php the_content('Read more...'); ?></p>
    </li>
    <?php endwhile; ?>

我想要做的是通过循环在第3次交互中向'last'元素添加一个名为<li>的类。

任何人都有任何想法我可以添加这个吗?

3 个答案:

答案 0 :(得分:3)

在while循环之外设置一个计数器

$count = 1;

检查该计数器的模数并在需要时输出该类

<li <?php if(!$count % 3) echo 'class="last"; ?>>

在关闭循环之前递增你的计数器:

    $count++;
}

或者,应用于您的代码:

<?php 
    $count = 1;
    while (have_posts()) : the_post(); 
?>
<li <?php if(!$count % 3) echo 'class="last"; ?>>
    <div class="imgholder">
        <a href="/wp-content/themes/twentyten/images/slide1.jpg" data-gal="prettyPhoto[featured]" title="<?php the_title(); ?>">
            <img src="<?php echo get_post_meta($post->ID, 'thumbnail',true) ?>" width="275" height="145" alt="Post Image" class="postimg-s" />
        </a>
    </div>
    <h4><?php the_title(); ?></h4>
    <p><?php the_content('Read more...'); ?></p>
</li>
<?php
    $count++; 
    endwhile; 
?>

模数条件的反直觉外观是,只要计数器可以被3整除,它就会返回0.

答案 1 :(得分:3)

替换

<li>

<li <?php print have_posts() ? '' : ' class="last"' ?>>
  

have_posts()只是打电话给   $wp_query->have_posts()检查a   循环计数器,看看是否有   帖子数组中剩余的帖子(source

答案 2 :(得分:0)

李应该是李

<li <?php $iCounterLi++; ($iCounterLi==3)?'class="last"':''; ?>>

不要忘记在循环之前初始化$ iCounterLi

相关问题