I’m trying to target the last item in a foreach loop but it’s acting a little strange.
I’ve got two items in the loop, I’ve tried the following:
- Not set a +/- for the count, this targets the first item.
- Using -1 as the count also targets the first item.
- Using +1 as the count doesn’t target any items until you add a 3rd
item, then it works as intended.
Here’s the code, can anyone help?
<?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order'));
foreach($pages as $key => $post)
{
setup_postdata($post);
$fields = get_fields();
?>
<div class="event<?php if( $key == (count( $pages ) +1) ) echo 'last'; ?>">
</div>
<?php } wp_reset_query(); ?>
This is the way to do it: