When developing WordPress themes, many developers like to create a user list to improve user activity on the site. Building a user list is simple enough with the get_users function. However, once the number of users becomes very large, displaying all of them on one page can make the page extremely slow to load. In that case, adding pagination to the user list becomes necessary. Many people run into trouble when trying to implement that pagination. Following the previous user-list example, let us now look at how to use WordPress’s paginate_links function.
First, query and display the user list, and prepare the pagination data at the same time
$number = 10; // Number of users per page
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // Current page
$offset = ($paged - 1) * $number; // Offset
$users = get_users(); // Get all users
$query = get_users('&offset='.$offset.'&number='.$number); // Users for the current page
$total_users = count($users); // Total number of users
$total_query = count($query); // Number returned in current query
$total_pages = intval($total_users / $number) + 1; // Total number of pages
foreach($query as $q) {
// Output the users
}
With those values prepared, use paginate_links() to output the pagination
The principle behind pagination does not need much explanation. The required values are simply the number of items per page, the total number of items, and the current page number. We already prepared all of that above, so now we just need to pass those parameters into paginate_links. Of course, if you really want to write raw SQL for the query, you can also use $wpdb to implement it directly.
if ($total_users > $total_query) {
echo '<div id="pagination" class="clearfix">';
echo '<span class="pages">Pages:</span>';
// Use the larger value between the first page and the queried page as the current page
$current_page = max(1, get_query_var('paged'));
// Output the pagination
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => 'page/%#%/',
'current' => $current_page,
'total' => $total_pages,
'prev_next' => false,
'type' => 'list',
));
echo '</div>';
}
Using the same approach, we can also implement pagination for WordPress category or tag lists. The same idea even works for paginating data from custom database tables in WordPress, because the paginate_links function can be used there too. And if you prefer to use your own pagination function or another pagination library, the underlying principle is still the same.
