Playing Nice With WordPress paginate_links function

Let’s say you want to add pagination to your theme but instead of just displaying “next” and “previous” links you’d rather show a list of pages to your users. The paginate_links() function will take care of that for you. However, out of the box it can be a bit tricky to figure out and the examples on the Codex page are not that great in my opinion. Here’s a snippet that we use in all of our themes to display a pagination list on the blog page template.

/*
 * This function displays pagination links based on arguments.
 * @uses paginate_links for output
 */
function my_blog_paginate_links( $return = false ) {
	global $wp_query;

	$pagination_links = paginate_links( array(
		'base' => esc_url( get_pagenum_link() ) . '%_%', // %_% will be replaced with format below
		'format' => ( ( get_option( 'permalink_structure' ) && ! $wp_query->is_search ) || ( is_home() && get_option( 'show_on_front' ) !== 'page' && ! get_option( 'page_on_front' ) ) ) ? '?paged=%#%' : '&paged=%#%', // %#% will be replaced with page number
		'current' => max( 1, get_query_var( 'paged' ) ), // Get whichever is the max out of 1 and the current page count
		'total' => $wp_query->max_num_pages, // Get total number of pages in current query
		'next_text' => 'Next →',
		'prev_text' => '← Previous',
		'type' => ( $return ) ? 'array' : 'list'  // Output this as an array or unordered list
	) );

	if( $return )
		return $pagination_links;
	else
		echo $pagination_links;
}

The above function will output a list of paginated links and works will no permalinks as well as pretty permalinks. We use a few conditional statements in the form of a ternary operator on the ‘format’ argument to determine if permalinks are enabled, we’re on a search page, or if the blog page is the front page. If you pass true as a parameter, an array of values will be returned instead of a list of paginated links. See the comments in the snippet for more information. You can use the function in one of your templates as seen here:

<?php my_blog_paginate_links(); ?>

About

I am the Lead Developer at Slocum Studio, a WordPress design and development firm located in Dartmouth, MA. We make high quality premium themes which you can find at http://slocumthemes.com. I have been working with WordPress for over 5 years and have experience in everything from creating themes to creating plugins, and everything in between.

2 thoughts on “Playing Nice With WordPress paginate_links function

  1. On line 10 it doesn’t make a differenz:
    [...] ? '?paged=%#%' : '&paged=%#%', // %#% will be replaced with page number

    better:
    [...] ? 'page/%#%' : '&paged=%#%', // %#% will be replaced with page number

Leave a Reply to Drivingralle Cancel reply

Your email address will not be published. Required fields are marked *