5

Im using the get_users function to show a custom list of users on the site. The only issue Im having a problem figuring out now is how to paginate the result.

This is a sample of the function that Im using:

Sample Code Screen shot

There doesn't seem to be an obvious way of creating a pagination for the this function. I would appreciate some help with this.

1 Answer 1

9

First get the total number of users:

$total_users = count_users();
//var_dump($total_users); //for debugging purpose
$total_users = $total_users['total_users'];

and the current page:

$paged = get_query_var('paged');

Set a variable that will decide how many users to display per page:

$number = 20; // ie. 20 users page page 

Then, in your $args array add the offset if the current page != 0, and the max number of users to return:

'offset' => $paged ? ($paged - 1) * $number : 0,
'number' => $number,

Now add your code from above, and create the page links:

// display the user list here

if($total_users > $number){

  $pl_args = array(
     'base'     => add_query_arg('paged','%#%'),
     'format'   => '',
     'total'    => ceil($total_users / $number),
     'current'  => max(1, $paged),
  );

  // for ".../page/n"
  if($GLOBALS['wp_rewrite']->using_permalinks())
    $pl_args['base'] = user_trailingslashit(trailingslashit(get_pagenum_link(1)).'page/%#%/', 'paged');

  echo paginate_links($pl_args);
}

See paginate_links() for a full list of arguments....

3
  • 2
    This was awesome and pointed me in the right direction, but it removes the second page of results how it was originally set up. Mainly $pl_args['total'] should be "ceil" not "floor" since it is the total pages. And then 'offset' for the get_user $args should be 'offset' => $paged ? ($paged-1) * $number : 0,. You need to remove 1 from $paged to get 0,1,2,3 instead of 0,2,3,4.
    – Jake
    Commented Nov 11, 2013 at 18:51
  • Thank you very much for the working and awesome snippet. Am using it in custom wordpress page backend created by add_menu_page and when navigating to the next page it says "Sorry, you are not allowed to access this page.". How i can solve this issue? Thanks
    – Ana DEV
    Commented Nov 24, 2017 at 12:49
  • Thank you @onetrickpony. Your code works Commented Aug 18, 2020 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.