Jul 7, 2011

How To Add Simple Pagination To WordPress

Many sites uses pagination to navigate to the older posts. If you install twenty ten or twenty eleven default wp theme, then you will notice that instead of pagination, it gives you old fashion links.
So to have pagination write the below function to your functions.php file

 

[php]function paginate() {
global $wp_query, $wp_rewrite;
$wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;

$pagination = array(
'base' => @add_query_arg('page','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'show_all' =>true,
'type' =>'list',
'next_text' => '»',
'prev_text' =>'«'
);

if( $wp_rewrite->sing_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );

if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array( 's' => get_query_var( 's' ) );

echo paginate_links( $pagination );
}[/php]

After some PHP code, we will need to add some CSS styling, so it gets the looks of actual pagination.
So add the following CSS code to your style.css file

 

[php]/* Pagination */

ul.page-numbers {
margin: 20px 0 10px;
width: 100%;
padding: 0;
font-size: 12px;
line-height: normal;
clear: both;
float: left;
}

ul.page-numbers li {
float: left;
}

ul.page-numbers a,
ul.page-numbers span {
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
background: -webkit-gradient(linear, left top, left bottom, from(#E4E3E3), to(#FFFFFF));
background: -moz-linear-gradient(top, #E4E3E3, #FFFFFF);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E4E3E3', endColorstr='#FFFFFF');
padding: 3px 4px 2px 4px;
margin: 2px;
text-decoration: none;
border: 1px solid #ccc;
color: #666;
}

ul.page-numbers a:hover,
ul.page-numbers span.current {
border: 1px solid #666;
color: #444;
}[/php]

The above CSS is really simple, if you want to make your pagination to match your theme, then simply edit the CSS. Its damn Simple.
To include the pagination, we need to call the function.
So if you are going to display the pagination on the home dynamic page, then goto index.php file, and replace the below function with your old boring pagination.

[php]
<?php paginate(); ?>
[/php]

To know more about paginate_links()
Refer the Codex: http://codex.wordpress.org/Function_Reference/paginate_links

No comments :

Post a Comment