Pagination Using paginate_links()

There are often posts on the WP Support forum asking how to paginate a custom query or an array. Here is a link to an article with one solution: Pagination Without Using A Plugin

The code below shows an example of using the built-in WP function paginate_links() for this purpose.

<?php
// Test the use of paginate_links

$rows_per_page = 7;
$current = (intval(get_query_var('paged'))) ? intval(get_query_var('paged')) : 1;

// $rows is the array that we are going to paginate.
$rows = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");

global $wp_rewrite;

$pagination_args = array(
 'base' => @add_query_arg('paged','%#%'),
 'format' => '',
 'total' => ceil(sizeof($rows)/$rows_per_page),
 'current' => $current,
 'show_all' => false,
 'type' => 'plain',
);

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

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

echo paginate_links($pagination_args);

$start = ($current - 1) * $rows_per_page;
$end = $start + $rows_per_page;
$end = (sizeof($rows) < $end) ? sizeof($rows) : $end;

echo '<br />';
for ($i=$start;$i < $end ;++$i ) {
 $row = $rows[$i];
 echo "I:$i  ID:{$row->ID}  Title:{$row->post_title} <br />";

}
?>

26 Responses to Pagination Using paginate_links()

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>