The Quick and Dirty Way
The following code was taken directly from the WordPress codex here. Just paste this code wherever you would like your paginated links to appear.
<?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
) );
?>
A Cleaner Approach
Add the following to functions.php in your theme directory:
if ( ! function_exists( 'my_pagination' ) ) :
function my_pagination() {
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
) );
}
endif;
Now you can call the function in your files like so:
<?php my_pagination(); ?>
Adding Pagination To A Custom Page Template
If you’re trying to add pagination to a custom page template, make sure you’re using query_posts() and not wp_query(). Here’s an example of the type of loop you should be using in order to get pagination to work on a custom page template.
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array(
'post_type' => 'post', // You can add a custom post type if you like
'paged' => $paged,
'posts_per_page' => 10
));
if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php // post content goes here ?>
<?php endwhile; ?>
<?php my_pagination(); ?>
<?php else : ?>
<?php // no posts found message goes here ?>
<?php endif; ?>
Bonus: TwentyTwelve Theme
TwentyTwelve is currently the default WordPress theme at the time this writing. To easily paginate TwentyTwelve, just add the following code to the top of functions.php, directly below the opening <?php tags.
if ( ! function_exists( 'twentytwelve_content_nav' ) ) :
function twentytwelve_content_nav() {
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
) );
}
endif;
If you are using a child theme with TwentyTwelve, you don’t have to worry about the placement of the above code. Just make sure it’s in your child theme’s functions.php file (anywhere below the opening <?php tags).
Still Having Trouble?
If you still can’t get your pagination to work, feel free to leave a comment and I’ll try and help you out. Also, do yourself a favor and make sure you have a clear understanding of the WordPress template heirarchy, as well as both query_posts() and wp_query().
Enjoyed this article?
Check out the latest on how to search WordPress by custom fields without a plugin.