List users with WP_User_Query


WordPress 3.1 included a new cool class called WP_User_Query. As the name implies, it allows querying the WordPress User database trough it’s available methods. It’s a much welcome addition which deprecates WP_User_Search and makes it very easy to retrieve specific users from the database.

Here is a simple example of WP_User_Query in action:

// prepare arguments
$args  = array(
// search only for Authors role
'role' => 'Author',
// order results by display_name
'orderby' => 'display_name',
// check for two meta_values
'meta_query' => array(
	array(
		// uses compare like WP_Query
		'key' => 'some_user_meta_key',
		'value' => 'some user meta value',
		'compare' => '>'
		),
	array(
		// by default compare is '='
		'key' => 'some_other_user_meta_key',
		'value' => 'some other meta value',
		),
	// add more
));
// 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 '<ul>';
	// loop trough each author
	foreach ($authors as $author)
	{
		// get all the user's data
		$author_info = get_userdata($author->ID);
		echo '<li>'.$author_info->first_name.' '.$author_info->last_name.'</li>';
	}
	echo '</ul>';
} else {
	echo 'No authors found';
}

Parameters

To tweak the search terms the WP_User_Query constructor allows the following parameters:

blog_id (int)
The blog id on a multisite environment. Defaults to the current blog id.

role (string)
The user’s role.

meta_key (string)
meta_value (string)
meta_compare (string)
Same as WP_Query ( view ).

include (array)
Array of users id to include.

exclude (array)
Array of users id to exclude.

search (string)
Searches for possible string matches on columns user_email, user_login,ID,user_url, user_login and user_nicename.

orderby (string)
login, 'nicename', 'email', 'url', 'registered'. Defaults to login.

order (string)
Defaults to ASC (ascending order).

offset (int)
Offset results ( handy for pagination ).

count_total (boolean)
If true returns the total of users found.

number (int)
Limit of users to retrieve.

fields (all)
Which fields to return. Defaults to all.

Conclusion

Now it’s awesomely simple to create users listings. I would suggest pagination and caching results for websites with lots of users as these queries can get pretty heavy.

Hope you find the code useful, if you have any comments or suggestions please feel free to leave them in the comments. Thanks for reading!

Reactions (5)

  1. Hi Matt

    Good article! I’m using a similar code snippet (which works fine) but also with pagination (which doesn’t!).

    Unfortunately, I think WP_User_Query does not work the same as WP_Query in regards to pagination and I cannot find any documentation which tells me either way.

    You mentioned we should use pagination so I’m wondering if you also know how and if you can update your article to tell us?

    yours hopefully

  2. Matthew Burrows

    Hi Matt,

    This is rad. Much better than having to write your own SQL.

    Thanks for writing this article!

    Matt.

  3. Thanks, Matt! This was super helpful. In case anyone is still looking how to paginate, Here’s the solution I put together from Matt’s and 2 other sources. It was important to set $paged, as well as change the standard pagenavi to ‘users’ ) ); ?>

    $limit,’offset’ => $offset);
    // Create the WP_User_Query object
    global $wp_query;
    $wp_query = new WP_User_Query($args);
    // Get the results
    $authors = $wp_query->get_results();
    if($authors): ?>

    ID);
    echo $author_info->user_firstname.’ ‘.$author_info->user_lastname?>

    No participants found.

    ‘users’ ) ); ?>

    Sources:

    (pagination solution. Took out the edit to functions.php)
    http://wordpress.stackexchange.com/questions/30977/list-users-by-last-name-in-wp-user-query/31081#31081

    (WP-PageNavi version 2.80)
    http://scribu.net/wordpress/wp-pagenavi/wpn-2-80.html
    https://github.com/scribu/wp-pagenavi/blob/master/core.php

  4. Dominor Novus

    I need to implement a select form field that populates users by their display names (the value for each option is the user ID).

    I can achieve this using your previous method outline here:

    http://www.mattvarone.com/wordpress/list-users/

    This is my code:

    Select a user
    get_col( $wpdb->prepare(
    // "SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY %s DESC"
    // , $szSort ));
    "SELECT $wpdb->users.ID FROM $wpdb->users ORDER BY display_name"
    ));

    /*
    Once we have the IDs we loop through them with a Foreach statement.
    */
    foreach ( $aUsersID as $iUserID ) :
    /*
    We use get_userdata() function with each ID.
    */
    $user = get_userdata( $iUserID );
    /*
    Here we finally print the details wanted.
    Check the description of the database tables linked above to see
    all the fields you can retrieve.
    To echo a property simply call it with $user->name_of_the_column.
    In this example I print the first and last name.
    */
    // echo '' . ucwords( strtolower( $user->display_name . ' ' . $user->last_name ) ) . '';
    echo 'ID.'">'.$user->display_name .'';
    /*
    The strtolower and ucwords part is to be sure
    the full names will all be capitalized.
    */
    endforeach; // end the users loop.
    ?>

    Do you have any suggestions on how to implement this using WP_User_Query. I tried editing the argument but my page keeps on breaking.