WordPress Custom Post Query With Numbered Pagination

About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.

WordPress Custom Post Query With Numbered Pagination

A question that often comes up – how to write a proper WordPress query with pagination.  Here’s a quick guide to get the job done:

We’ll start by putting together the array of what we’re looking to pull in.  For this example, we’ll just be pulling in the standard post post type and limiting our results per page to 20:

if ( get_query_var('paged') ) $paged = get_query_var('paged');
if ( get_query_var('page') ) $paged = get_query_var('page');
$args = array(
'posts_per_page' => 20,
'paged' => $paged
<?php if ( have_posts() ) :  while (have_posts()) : the_post();?>

Next, you’ll want to loop through your query as you normally do printing out the title, content, featured image, etc..

Once the loop is finished, we’ll close out the loop and output our pagination.  Notice the first IF statement that checks if there are more than one pages of posts being returned, if not, it doesn’t output the pagnination:

<?php endwhile; ?>

<?php if( $wp_query->max_num_pages > 1 ) { ?>
<ul class="page-numbers brd-box text-center">
<?php global $wp_query;

$big = 999999999; // need an unlikely integer

echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages
) ); ?>
<?php } ?>

// Wrapping up the query and resetting to avoid conflicts
<?php endif; wp_reset_query(); ?>

And that’s it.  Short, simple and to the point.  You’ll now get a great query with numbered pagination.

Share Your Thoughts

Leave a Reply

Your email address will not be published.

Related Stuff You Might Like

WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!