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)
    {
    setup_postdata($post);
    $fields = get_fields();
?>
<div class="event">
    <img class="event-thumbimage" src="https://wordpress.stackexchange.com/questions/24293/<?php echo $fields->thumb_image; ?>" height="120" width="140" alt="<?php echo $fields->event_title; ?>" />
    <h2><?php echo $fields->event_title; ?></h2>
    <p>
        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>                        
    <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>
</div>
<?php } wp_reset_query(); ?>

2 Answers
2

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.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *