Getting last item in count variable

So I’m using WordPress and created a variable $post_count to track the number of posts.

Right now I’m using if($post_count == 1) to add a class if it’s the first post, which works fine, but I can’t figure out how to get the last post.

Read More

Would that be possible using just a variable to count posts? Or is there a better way to do this than creating a count variable? Here’s my code so far:

if($query->have_posts()): $post_count = 0; ?>
    <div class="image-grid">
        <?php while($query->have_posts()): $post_count++; $query->the_post(); ?>
        <div class="item <?php if($post_count == 1) { ?>first_item<?php 
        } elseif() { ?>last item<?php } ?>">post content here</div>
        <?php endwhile; ?>
    </div>
<?php endif; ?>

Related posts

Leave a Reply

2 comments

  1. <?php if($query->have_posts()): $post_count = 0; ?>
        <div class="image-grid">
            <?php while($query->have_posts()): 
                $post_count++; 
                $query->the_post(); 
                ?>
                <div class="item <?php if($post_count == 1) { echo 'first_item'; } if( $query->found_posts == $post_count ) { echo 'last item'; } ?>">
                    <?php //post content here ?>
                </div>
            <?php endwhile; ?>
        </div>
    <?php endif; ?>