WordPress: Check If Last Post In Loop
WordPress really is one of the best, user-friendly CMS’s / blogging platforms to have ever been created.
Everything is easily accomplished (generally) and their documentation is great.
You will, however, run into small issues when developing, that leave you going “huhhhhh”?
This may be one of those small issues. So let’s get on to addressing it and supplying an easy solution!
In your theme, do you have a loop that looks something like this?
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> ... <h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1> <?php the_content(); ?> ... <?php endwhile; ?>
Most indexes / front pages on WordPress websites are similarly setup. This particular example, is very simplistic, but go with it anyway. At its current state, it will plop together posts fine, but there is no spacing whatsoever in between posts. How about we add a horizontal line to separate them?
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> ... <h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1> <?php the_content(); ?> ... <hr /> <?php endwhile; ?>
Neat. That solves our problem of creating separation between posts on the front page! Well, almost. You may notice that there is a horizontal line after the last post too (even no posts exist after it). That looks…pretty ugly. So how do we detect when the last post occurs so that we can avoid that extra HR?
There are two ways of going about this. One could be to use a variable as a counter that will keep track of what post you are on, and then (once the final post is reached), does not output the HR. This only works if you reach your maximum post count though. If you don’t know how many posts will be on the page, then that just doesn’t work.
So a better solution? Add the following code to your functions.php for your theme:
function more_posts() { global $wp_query; return $wp_query->current_post + 1 < $wp_query->post_count; }
This function returns the total amount of posts available after the current post. Now, let’s modify that loop from earlier to use this!
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> ... <h1><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1> <?php the_content(); ?> ... if ( more_posts() != 0 ) { echo '<hr class="post-separator" />'; } <?php endwhile; ?>
Boom! Done. It’s a nice, re-usable function.