10

I think I'm nearly there with this, but I can't get the pagination links to show for a directory of authors I'm creating.

My code is below, but I don't know how to get the links to navigate between pages of authors to work. Can anyone help me? I've got the feeling this might be of use, but I don't know how to implement it:

paginate_links()

Thanks

Osu

    <?php 
/* ****************************************************************** */
                        /* !LIST AUTHORS */
/* ****************************************************************** */ 

// THANKS TO:
// http://www.mattvarone.com/wordpress/list-users-with-wp_user_query/

// pagination
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // Needed for pagination
$paged -= 1;
$limit = 2;
$offset = $paged * $limit;

// prepare arguments
$args  = array(
    // search only for Authors role
    'role'      => 'Subscriber',
    // order results by display_name
    'orderby'   => 'display_name',
    // return all fields
    'fields'    => 'all_with_meta',
    'number'    => $limit,
    'offset'    => $offset      
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);
// Get the results
$authors = $wp_user_query->get_results();
// Check for results
if (!empty($authors))
{
    echo '<div class="author-entry">';
    // loop trough each author
    foreach ($authors as $author)
    {
        $author_info = get_userdata($author->ID); ?>

        <span style="float:left;padding:0 5px 0 0;"><?php echo get_avatar( $author->ID, 50 ); /* http://codex.wordpress.org/Function_Reference/get_avatar */ ?></span>
        <span class="fn"><strong>First name</strong> : <?php echo $author_info->first_name; ?></span><br />
        <span class="ln"><strong>Last name</strong> : <?php echo $author_info->last_name; ?></span><br />
        <span class="em"><strong>Email address</strong> : <a href="mailto:<?php echo $author_info->user_email; ?>"><?php echo $author_info->user_email; ?></a></span><br />
        <span class="we"><strong>Website</strong> : <a href="<?php echo $author_info->user_url; ?>"><?php echo $author_info->user_url; ?></a></span><br />

        <span class="de"><strong>Bio</strong> :<br /><?php echo $author_info->description ; ?></span>
        <div class="clear">&nbsp;</div>

    <?php 
    }
    echo '</div>';
} else {
    echo 'No authors found';
}
?>

<?php /* WHAT DO I PUT HERE TO CREATE THE PAGINATION LINKS? */ ?>
17

This should get you really close. I haven't tested it, but it's nearly identical to a setup I've used a few times.

/*
 * We start by doing a query to retrieve all users
 * We need a total user count so that we can calculate how many pages there are
 */

$count_args  = array(
    'role'      => 'Subscriber',
    'fields'    => 'all_with_meta',
    'number'    => 999999      
);
$user_count_query = new WP_User_Query($count_args);
$user_count = $user_count_query->get_results();

// count the number of users found in the query
$total_users = $user_count ? count($user_count) : 1;

// grab the current page number and set to 1 if no page number is set
$page = isset($_GET['p']) ? $_GET['p'] : 1;

// how many users to show per page
$users_per_page = 5;

// calculate the total number of pages.
$total_pages = 1;
$offset = $users_per_page * ($page - 1);
$total_pages = ceil($total_users / $users_per_page);


// main user query
$args  = array(
    // search only for Authors role
    'role'      => 'Subscriber',
    // order results by display_name
    'orderby'   => 'display_name',
    // return all fields
    'fields'    => 'all_with_meta',
    'number'    => $users_per_page,
    'offset'    => $offset // skip the number of users that we have per page  
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);

// Get the results
$authors = $wp_user_query->get_results();

// check to see if we have users
if (!empty($authors))
{
    echo '<div class="author-entry">';
    // loop trough each author
    foreach ($authors as $author)
    {
        $author_info = get_userdata($author->ID); ?>

        <span style="float:left;padding:0 5px 0 0;"><?php echo get_avatar( $author->ID, 50 ); /* http://codex.wordpress.org/Function_Reference/get_avatar */ ?></span>
        <span class="fn"><strong>First name</strong> : <?php echo $author_info->first_name; ?></span><br />
        <span class="ln"><strong>Last name</strong> : <?php echo $author_info->last_name; ?></span><br />
        <span class="em"><strong>Email address</strong> : <a href="mailto:<?php echo $author_info->user_email; ?>"><?php echo $author_info->user_email; ?></a></span><br />
        <span class="we"><strong>Website</strong> : <a href="<?php echo $author_info->user_url; ?>"><?php echo $author_info->user_url; ?></a></span><br />

        <span class="de"><strong>Bio</strong> :<br /><?php echo $author_info->description ; ?></span>
        <div class="clear">&nbsp;</div>

    <?php 
    }
    echo '</div>';
} else {
    echo 'No authors found';
}

// grab the current query parameters
$query_string = $_SERVER['QUERY_STRING'];

// The $base variable stores the complete URL to our page, including the current page arg

// if in the admin, your base should be the admin URL + your page
$base = admin_url('your-page-path') . '?' . remove_query_arg('p', $query_string) . '%_%';

// if on the front end, your base is the current page
//$base = get_permalink( get_the_ID() ) . '?' . remove_query_arg('p', $query_string) . '%_%';

echo paginate_links( array(
    'base' => $base, // the base URL, including query arg
    'format' => '&p=%#%', // this defines the query parameter that will be used, in this case "p"
    'prev_text' => __('&laquo; Previous'), // text for previous page
    'next_text' => __('Next &raquo;'), // text for next page
    'total' => $total_pages, // the total number of pages we have
    'current' => $page, // the current page
    'end_size' => 1,
    'mid_size' => 5,
));
  • 2
    +1 Would've enjoyed if the code would be splitted and explained :) – kaiser Jul 4 '12 at 20:28
  • 5
    There, added some better comments and fixed a bug or two :) – Pippin Jul 4 '12 at 20:53
  • Thanks for this @Pippin, I'll try it out when I get in the studio. One question: what do I put in the 'your-page-path' part of the admin_url? Is that the root of my site? – Osu Jul 5 '12 at 16:02
  • Is the page that is showing your users in the admin or on the front end? – Pippin Jul 5 '12 at 20:10
  • 1
    Interesting approach. I noticed you're running 2 queries here: the first to get all users and the second to get only the users on the appropriate page. Wouldn't it perform better if you used only 1 query and then used array_slice to split up the results into pages? It seems since you're performing 2 different queries on the same data that you could save some performance by dropping one. – codescribblr Jun 22 '15 at 2:35
8

You really should not use the answer by Pippin. The query is very inefficient. $user_count_query in the example can return up to 999,999 users from your database to your script, with all of the user fields. This will surely hit memory and/or time limits for PHP if/when your site grows large enough.

But that may have been the only solution back in 2012.

Here is a better way to do it. In this example I've only got next and previous page but if you do need numbered pagination, the variables are there to build it out. WordPress doesn't have a pagination function that is compatible with WP_User_Query (to my knowledge).

<?php

// Pagination vars
$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;
$users_per_page = 2; // RAISE THIS AFTER TESTING ;)

$args = array(
    'number' => $users_per_page, // How many per page
    'paged' => $current_page // What page to get, starting from 1.
);

$users = new WP_User_Query( $args );

$total_users = $users->get_total(); // How many users we have in total (beyond the current page)
$num_pages = ceil($total_users / $users_per_page); // How many pages of users we will need

?>
    <h3>Page <?php echo $current_page; ?> of <?php echo $num_pages; ?></h3>
    <p>Displaying <?php echo $users_per_page; ?> of <?php echo $total_users; ?> users</p>

    <table>
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
            </tr>
        </thead>

        <tbody>
            <?php
            if ( $users->get_results() ) foreach( $users->get_results() as $user )  {
                $firstname = $user->first_name;
                $lastname = $user->last_name;
                $email = $user->user_email;
                ?>
                <tr>
                    <td><?php echo esc_html($firstname); ?></td>
                    <td><?php echo esc_html($lastname); ?></td>
                    <td><?php echo esc_html($email); ?></td>
                </tr>
                <?php
            }
            ?>
        </tbody>
    </table>

    <p>
        <?php
        // Previous page
        if ( $current_page > 1 ) {
            echo '<a href="'. add_query_arg(array('paged' => $current_page-1)) .'">Previous Page</a>';
        }

        // Next page
        if ( $current_page < $num_pages ) {
            echo '<a href="'. add_query_arg(array('paged' => $current_page+1)) .'">Next Page</a>';
        }
        ?>
    </p>

Example showing page 2:

table of users, starting at page 2


Update 6/8/2018: How to add page numbers instead of Next/Previous

If you want to have page numbers instead of next/previous page links, here is how you can set that up. Note that you will need to replace the numbers with page links, they will not be clickable in this example (based on https://stackoverflow.com/a/11274294/470480, modified to show a consistent amount of middle numbers and not add the "..." unless a page is actually skipped).

You can also see my gist file which contains a reusable function for this purpose.

$current_page = 5; // Example
$num_pages = 10; // Example

$edge_number_count = 2; // Change this, optional

$start_number = $current_page - $edge_number_count;
$end_number = $current_page + $edge_number_count;

// Minus one so that we don't split the start number unnecessarily, eg: "1 ... 2 3" should start as "1 2 3"
if ( ($start_number - 1) < 1 ) {
    $start_number = 1;
    $end_number = min($num_pages, $start_number + ($edge_number_count*2));
}

// Add one so that we don't split the end number unnecessarily, eg: "8 9 ... 10" should stay as "8 9 10"
if ( ($end_number + 1) > $num_pages ) {
    $end_number = $num_pages;
    $start_number = max(1, $num_pages - ($edge_number_count*2));
}

if ($start_number > 1) echo " 1 ... ";

for($i=$start_number; $i<=$end_number; $i++) {
    if ( $i === $current_page ) echo " [{$i}] ";
    else echo " {$i} ";
}

if ($end_number < $num_pages) echo " ... {$num_pages} ";

Output (from page 1 to 10):

[1]  2  3  4  5  ... 10 
1  [2]  3  4  5  ... 10 
1  2  [3]  4  5  ... 10 
1  2  3  [4]  5  ... 10 

1 ...  3  4  [5]  6  7  ... 10 
1 ...  4  5  [6]  7  8  ... 10 

1 ...  6  [7]  8  9  10
1 ...  6  7  [8]  9  10
1 ...  6  7  8  [9]  10
1 ...  6  7  8  9  [10]
  • I agree. Pippin's answer requires 2 hits on the db which should be avoided if possible. – The Sumo Aug 18 '17 at 15:16
  • 1
    Hi @radley-sustaire, this is a great solution, but I was wondering if there is a way to change the "displaying 2 of 6 users" part to the actual range of users per page. So something like "displaying 1-2 of 6" for page 1, "3-4 of 6" for page 2 and "5-6 of 6" for page 3. At the moment, it just shows "2 of 6" for all pages. – damienoneill2001 Feb 13 '18 at 10:50
  • 1
    @damienoneill2001 That's a good idea, you can start with something like: $start_user_num = (($current_page-1) * $users_per_page) + 1; and $end_user_num = $start_user_num + count($users->get_results());. – Radley Sustaire Feb 13 '18 at 23:04
  • @RadleySustaire excellent, thanks for that. At first, I received the following error: Call to a member function get_results() on a non-object so I amended $end_user_number to $start_user_num + ($users_per_page-1); and that solved the problem. Thanks again! – damienoneill2001 Feb 14 '18 at 11:42
  • Turns out I spoke to soon on that. When I get to the final page that does not contain a full list of users, it obviously shows the wrong figure for the $end_user_number in my solution. Back to the drawing board, ha! – damienoneill2001 Feb 14 '18 at 13:41
1

Full credit should go to @radley-sustaire for his answer, but I spotted a small glitch with it so I'm sharing my version of the answer here.

With my version I was also filtering results by location, keyword etc so some pages had less results than the '$users_per_page' var. So for example if my users per page was set to show 10, but the results of the filter only returned 3 users, I got 'Displaying 10 of 3 users' at the top of the page. Obviously this didn't make sense so I added a simple "if" statement to check if the results count was higher than the '$users_per_page' variable.

Radley, if you edit your answer with the update, I will happily vote for it as the correct answer as I think it is better than Pippin's solution.

So this is the final code for anyone that wants it.

<?php

// Pagination vars
$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;
$users_per_page = 10;

$args = array(
    'number' => $users_per_page, // How many per page
    'paged' => $current_page // What page to get, starting from 1.
);

$users = new WP_User_Query( $args );

$total_users = $users->get_total(); // How many users we have in total (beyond the current page)
$num_pages = ceil($total_users / $users_per_page); // How many pages of users we will need

if ($total_users < $users_per_page) {$users_per_page = $total_users;}

?>
    <h3>Page <?php echo $current_page; ?> of <?php echo $num_pages; ?></h3>
    <p>Displaying <?php echo $users_per_page; ?> of <?php echo $total_users; ?> users</p>

    <table>
        <thead>
            <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
            </tr>
        </thead>

        <tbody>
            <?php
            if ( $users->get_results() ) foreach( $users->get_results() as $user )  {
                $firstname = $user->first_name;
                $lastname = $user->last_name;
                $email = $user->user_email;
                ?>
                <tr>
                    <td><?php echo esc_html($firstname); ?></td>
                    <td><?php echo esc_html($lastname); ?></td>
                    <td><?php echo esc_html($email); ?></td>
                </tr>
                <?php
            }
            ?>
        </tbody>
    </table>

    <p>
        <?php
        // Previous page
        if ( $current_page > 1 ) {
            echo '<a href="'. add_query_arg(array('paged' => $current_page-1)) .'">Previous Page</a>';
        }

        // Next page
        if ( $current_page < $num_pages ) {
            echo '<a href="'. add_query_arg(array('paged' => $current_page+1)) .'">Next Page</a>';
        }
        ?>
    </p>

protected by Community Sep 14 '17 at 20:18

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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