Paginating WordPress

After many Google searches and working out my own pagination code, I came across WordPress’s pre-built function paginate_links. If you think using “Previous Page/Next Page” is a little too generic, you’ll want to make use of this function.

In this post, I’ll show you how to quickly create your own set of paginated links.

*Note: You can download a zip file containing the the following code (at the bottom of this post). I have built a child theme of the default TwentyEleven theme that replaces the “Previous/Next” page with paginated links.


Step 1
Insert the following code into your functions.php file.

function m4c_pagination() {

// Get total number of pages
global $wp_query;
$total = $wp_query->max_num_pages;

// If there is more than 1 page, display the links
if ( $total > 1 ) {

// Get the current page
if ( !$current_page = get_query_var( 'paged' ) )
$current_page = 1;

// Get the user defined page structure
$structure = get_option( 'permalink_structure' );
$format = empty( $structure ) ? '&page=%#%' : 'page/%#%/';

// Create the base structure
$base = get_pagenum_link(1) . '%_%';

// Modify base structure if search or archive page
if ( is_search() || is_archive() ) {
$big = 999999999; // need an unlikely integer
$base = str_replace( $big, '%#%', get_pagenum_link( $big ) );
}

$args = array(
'base' => $base,
'format' => $format,
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'list',
'prev_text' => __( 'Previous', 'm4c_paginate_test' ),
'next_text' => __( 'Next', 'm4c_paginate_test' )
);

// Display the links
echo paginate_links( $args );
}
}

Step 2
Add some styling to your style.css file.

ul.page-numbers {
display: inline-block;
list-style: none;
background: url( assets/img/pattern.png );
margin: 20px 0;
padding: 10px;

-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
ul.page-numbers li,
ul.page-numbers li a,
ul.page-numbers li span {
font-size: 12px;
line-height: 12px;
color: #FFF;
}
ul.page-numbers li {
float: left;

}
ul.page-numbers li a {
text-decoration: none;
margin: 0 10px;
}
ul.page-numbers li a:hover {
color: #1982D1;
}
ul.page-numbers li a.next {

}
ul.page-numbers li span.current {
color: #1982D1;
font-weight: bold;
margin: 0 10px;
}
ul.page-numbers li span.next {

}

Step 3
Add the pagination function to your index.php page (or another page that displays multiple posts).

// Add custom pagination
m4c_pagination();

Resources
http://codex.wordpress.org/Function_Reference/paginate_links

Download1

Leave a Reply

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

Back To Top