This website uses cookies to allow us to see how the site is used. If you continue to use this site, we assume that you are okay with this. If you want to use the sites without cookies, please see our privacy policy.

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;
		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(); ?>