Loop add .last class to last item in loop
Im using wordpress and using the following to get the last 3 most recent posts:
<?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_conten开发者_StackOverflowt('Read more...'); ?></p>
</li>
<?php endwhile; ?>
What I want to do is add a class named 'last'
to the <li>
element on the 3rd interation through the loop.
Anyone got any ideas how I could add this?
Setup a counter outside your while loop
$count = 1;
Check the modulus of that counter and output the class if required
<li <?php if(!$count % 3) echo 'class="last"; ?>>
Increment your counter before closing the loop:
$count++;
}
Or, applied to your code:
<?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;
?>
The counter-intuitive look of the modulus condition is that whenever the counter is divisible by exactly 3 it will return 0.
Replace the line
<li>
with
<li <?php print have_posts() ? '' : ' class="last"' ?>>
The
have_posts()
simply calls into$wp_query->have_posts()
which checks a loop counter to see if there are any posts left in the post array (source)
Li should be li
<li <?php $iCounterLi++; ($iCounterLi==3)?'class="last"':''; ?>>
Don't forgot to initialize the $iCounterLi before the loop
精彩评论