Skip to main content Skip to secondary navigation Accessibility Feedback

Checking for pagination and the last post in WordPress

Today, I want to share two simple functions you can use to check if pagination exists on a particular page, and also check if a particular post is the last one on the page.

Creating your helper functions #

Add these functions to your functions.php file:

/**
 * If more than one page exists, return TRUE.
 */
function is_paginated() {
    global $wp_query;
    if ( $wp_query->max_num_pages > 1 ) {
        return true;
    } else {
        return false;
    }
}

/**
 * If last post in query, return TRUE.
 */
function is_last_post($wp_query) {
    $post_current = $wp_query->current_post + 1;
    $post_count = $wp_query->post_count;
    if ( $post_current == $post_count ) {
        return true;
    } else {
        return false;
    }
}

In your template files #

To check if a page is paginated, use this conditional script:

<?php if ( is_paginated() ) : ?>
    // Do stuff...
<?php endif; ?>

To check if a post is the last one on the page, include this snippet in the Loop:

<?php if ( is_last_post($wp_query) ) : ?>
    // Do stuff...
<?php endif; ?>

Why would you need this? #

On the design of this site at time of writing, I add an <hr> element between all posts except the last one, like this:

<?php if ( !is_last_post($wp_query) ) : ?>
    <hr>
<?php endif; ?>

Similarly, I’ll add page navigation on paginated sections only:

<?php if ( is_paginated() ) : ?>
    <nav>
        <hr>
        <p class="text-center"><?php posts_nav_link( '   •   ', '← Newer', 'Older →' ); ?></p>
    </nav>
<?php endif; ?>

Hope that helps!

  • More articles on...
  • Code

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Weekly Digests