I have the following code to do a foreach loop, I want to target the last item in the loop (e.g if it's looped over 3 events I want to target the 3rd event) to do something slightly different with the css. How would I do that?

<?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
    foreach($pages as $post)
    $fields = get_fields();
<div class="event">
    <img class="event-thumbimage" src="<?php echo $fields->thumb_image; ?>" height="120" width="140" alt="<?php echo $fields->event_title; ?>" />
    <h2><?php echo $fields->event_title; ?></h2>
        Location: <?php echo $fields->location; ?><br />
        Start: <?php echo $fields->start_date; ?> at <?php echo $fields->start_time; ?>
        <?php $fields = get_acf(); if($fields->end_date != "") : ?>
        , End: <?php echo $fields->end_date; ?> at <?php echo $fields->end_time; ?>
        <?php else : ?>
        <?php endif; ?>
    <p style="margin-bottom:0px!IMPORTANT;"><?php echo substr($fields->description,0,170) . "..."; ?></p>
    <p><a class="read-more" href="<?php echo get_page_link($post->ID); ?>" title="Read more about: <?php echo $fields->event_title; ?>">Read more...</a></p>
<?php } wp_reset_query(); ?>

You can try this :

foreach( $pages as $key => $post )

and :

<div class = "event <?php if( $key == ( count( $pages ) - 1 ) ) echo 'last'; ?>" >

It will add a last class to your last event div.

  • Thanks, oddly it's added the last class to the 2nd item rather the 3rd one (i.e the last item). – Rob Jul 28 '11 at 9:45
  • 1
    Ah yes, that's because $key starts at zero, not one. I fixed the code. Tell me if it works now. – mike23 Jul 28 '11 at 10:02
  • 1
    should be if( $key == (count( $pages ) -1) ) since the array's first index is 0 while count functions starts from 1. – Bainternet Jul 28 '11 at 10:03
  • @Bainternet Thanks, knew what to do but couldn't get the syntax right! – Rob Jul 28 '11 at 10:05
  • @Bainternet It's acting a little strange. Using -1 as the count it makes the first item "last". When changing it to +1, it doesn't work when there's only two items in the list but works when there's 3, argh!! – Rob Jul 28 '11 at 12:51

Since $pages is an array, get its count by $pages_count = count( $pages ); and then inside loop, keep a counter which is incremented at every iteration of the loop and compare if it equals the count if ( $pages_count == $counter++ )

  • Thanks, not quite sure how to implement that. The items are unlimited so it's not necessarily the 3rd item, just the last item. – Rob Jul 28 '11 at 9:35

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.