Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using the following code to display the latest 3 blog posts on my front page but I need to add a last class to the 3rd post on the ID blog.

<?php
$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
foreach($lastposts as $post) : setup_postdata($post); ?>

<div id="blog">
  <div class="blog-header"><a href="<?php the_permalink(); ?>">
    <?php the_title(); ?>
    </a>
    <div class="date">
      <?php the_date(); ?>
    </div>
  </div>
  <?php the_excerpt(); ?>
</div>
<?php endforeach; ?>

What do I need to add to achieve this?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Something like this should work for you.

$args = array( 'numberposts' => 3 );
$lastposts = get_posts( $args );
$count = 1;
foreach($lastposts as $post) : setup_postdata($post); ?>

<div id="blog" class="<?php if ($count == 3) : ?>last<?php endif; ?>">
  <div class="blog-header"><a href="<?php the_permalink(); ?>">
    <?php the_title(); ?>
    </a>
    <div class="date">
      <?php the_date(); ?>
    </div>
  </div>
  <?php the_excerpt(); ?>
</div>
<?php 
$count++;
endforeach; ?>
share|improve this answer
    
Tried this code but it has added the class last to the first post rather than the last? –  Vince Pettit Nov 23 '11 at 16:05
1  
Sorry about that, I didn't test it. I simplified the code to suit your purpose. You could also use the css psuedo class :last-child. Something like .blog-conatiner .blog:last-child { color:red; }. –  cbaigorri Nov 23 '11 at 16:14
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.