0

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?

1

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; ?>
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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