WordPress Custom Post Query With Numbered Pagination
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:
<?php 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 ); query_posts($args); ?> <?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 ) ); ?> </ul> <?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