WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Class Reference/WP User Query

Description

WP_User_Query is a class, defined in wp-includes/user.php, that allows querying WordPress database tables 'wp_users' and 'wp_usermeta'. This class was introduced in Version 3.1 and as a result, the WP_User_Search class got deprecated.

Usage

<?php
$args = array(
	.
	.
	.
);

// The Query
$user_query = new WP_User_Query( $args );

// User Loop
if ( ! empty( $user_query->get_results() ) ) {
	foreach ( $user_query->get_results() as $user ) {
		echo '<p>' . $user->display_name . '</p>';
	}
} else {
	echo 'No users found.';
}
?>

Methods and Properties

Properties

$query_vars
An associative array containing the query variables and their respective values, after parsing.
$results
An array containing a list of found users.
$total_users
Total number of found users for the current query.
$query_fields
SQL clauses for the return fields.
$query_from
SQL clauses
$query_where
SQL clauses
$query_orderby
SQL clauses for sorting retrieved users.
$query_limit
SQL clauses for limiting retrieved users.

Methods

get()
Retrieve query variable.
set()
Set query variable.
get_results()
Return the list of users.
get_total()
Return the total number of users for the current query.

Parameters

User Role Parameter

Show users associated with certain role.

  • role (string / array) - use User Role. An array or a comma-separated list of role names that users must match to be included in results. Note that this is an inclusive list: users must match *each* role. Default empty.
  • role__in (array) - An array of role names. Matched users must have at least one of these roles. Default empty array. (since Version 4.4).
  • role__not_in (array) - An array of role names to exclude. Users matching one or more of these roles will not be included in results. Default empty array. (since Version 4.4).

Display Administrator role users

$user_query = new WP_User_Query( array( 'role' => 'Administrator' ) );

Display Subscriber role users

$user_query = new WP_User_Query( array( 'role' => 'Subscriber' ) );

Display all users except Subscriber role users

$user_query = new WP_User_Query( array( 'role__not_in' => 'Subscriber' ) );

Include & Exclude Parameters

Show specific users.

  • include (array) - List of users to be included.
  • exclude (array) - List of users to be excluded.

Display specific users list

$user_query = new WP_User_Query( array( 'include' => array( 1, 2, 3 ) ) );

Display all users except a specific list of users

$user_query = new WP_User_Query( array( 'exclude' => array( 4, 5, 6 ) ) );

Blog Parameter

Show users associated with certain blog on the network.

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

Display users from blog 33

$user_query = new WP_User_Query( array( 'blog_id' => 33 ) );

Search Parameters

Search users.

  • search (string) - Searches for possible string matches on columns. Use of the * wildcard before and/or after the string will match on columns starting with*, *ending with, or *containing* the string you enter.
  • search_columns (array) - List of database table columns to matches the search string across multiple columns.
    • 'ID' - Search by user id.
    • 'user_login' - Search by user login.
    • 'user_nicename' - Search by user nicename.
    • 'user_email' - Search by user email.
    • 'user_url' - Search by user url.

We can use the user_search_columns filter to modify the search columns.

Display users based on a keyword search

$user_query = new WP_User_Query( array( 'search' => 'Rami' ) );

Display users based on a keyword search, only on login and email columns

$args = array(
	'search'         => 'Rami',
	'search_columns' => array( 'user_login', 'user_email' )
);
$user_query = new WP_User_Query( $args );

Pagination Parameters

Limit retrieved Users.

  • number (int) - The maximum returned number of results (needed in pagination).
  • offset (int) - Offset the returned results (needed in pagination).
  • paged (int) - When used with number, defines the page of results to return. Default 1. (since Version 4.4).

Display 10 users

$user_query = new WP_User_Query( array( 'number' => 10 ) );

Display 5 users starting from 25

$user_query = new WP_User_Query( array( 'number' => 5, 'offset' => 25 ) );

Order & Orderby Parameters

Sort retrieved Users.

  • orderby (string) - Sort retrieved users by parameter. Defaults to 'login'.
    • 'ID' - Order by user id.
    • 'display_name' - Order by user display name.
    • 'name' / 'user_name' - Order by user name.
    • 'include' - Order by the included list of user_ids (requires the include parameter) (since Version 4.1).
    • 'login' / 'user_login' - Order by user login.
    • 'nicename' / 'user_nicename' - Order by user nicename.
    • 'email' / 'user_email' - Order by user email.
    • 'url' / 'user_url' - Order by user url.
    • 'registered' / 'user_registered' - Order by user registered date.
    • 'post_count' - Order by user post count.
    • 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query (available with Version 3.7).
    • 'meta_value_num' - Note that a 'meta_key=keyname' must also be present in the query (available with Version 4.2).
  • order (string) - Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'ASC'.
    • 'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
    • 'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).

Display users sorted by Post Count, Descending order

$user_query = new WP_User_Query( array ( 'orderby' => 'post_count', 'order' => 'DESC' ) );

Display users sorted by registered, Ascending order

$user_query = new WP_User_Query( array ( 'orderby' => 'registered', 'order' => 'ASC' ) );

Date Parameters

Date queries are handled through to the WP_Date_Query object and are applied to the user_registered field.

Available since version 4.1.

  • date_query (array) - See the documentation for the WP_Query class.

Find users that registered during the last 12 hours:

$args = array(
    'date_query' => array( 
        array( 'after' => '12 hours ago', 'inclusive' => true )  
    )
);
$user_query = new WP_User_Query( $args );

Custom Field Parameters

Show users associated with a certain custom field.

The WP_Meta_Query class is used to parse this part of the query since 3.2.0, so check the docs for that class for the full, up to date list of arguments.

  • meta_key (string) - Custom field key.
  • meta_value (string) - Custom field value.
  • meta_compare (string) - Operator to test the 'meta_value'. See 'compare' below.
  • meta_query (array) - Custom field parameters (available with Version 3.5).
    • key (string) - Custom field key.
    • value (string|array) - Custom field value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' or 'NOT EXISTS')
    • compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS', and 'NOT EXISTS' ; 'REGEXP', 'NOT REGEXP' and 'RLIKE' were added in WordPress 3.7. Default value is '='.
      Note: Currently 'NOT EXISTS' does not always work as intended if 'relation' is 'OR' when, (1) using the 'role' parameter on single site installs, or (2) for any query on multisite. See ticket #23849.
      Note 2: with 'LIKE' the value parameter is change to '%<value>%'. So the string is searched anywhere in the custom field value. If value parameter contain a '%' it is escaped. So it bans to search a string beginning by some characters, for exemple... To construct this query you must use 'REGEXP' with a regular expression in value parameter (ex : '^n.*' matchs all values that beginning by "n" or "N").
    • type (string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'. You can also specify precision and scale for the 'DECIMAL' and 'NUMERIC' types (for example, 'DECIMAL(10,5)' or 'NUMERIC(10)' are valid).

Display users from Israel

$user_query = new WP_User_Query( array( 'meta_key' => 'country', 'meta_value' => 'Israel' ) );

Display users under 30 years old

$user_query = new WP_User_Query( array( 'meta_key' => 'age', 'meta_value' => '30', 'meta_compare' => '<' ) );

Multiple custom user fields handling

$args = array(
	'meta_query' => array(
		'relation' => 'OR',
			array(
				'key'     => 'country',
				'value'   => 'Israel',
	 			'compare' => '='
			),
			array(
				'key'     => 'age',
				'value'   => array( 20, 30 ),
				'type'    => 'numeric',
				'compare' => 'BETWEEN'
			)
	)
 );
$user_query = new WP_User_Query( $args );

Who Parameter

Which users?

  • who (string) - Which users to query. Currently only 'authors' is supported. Default is all users.

Display only authors

$user_query = new WP_User_Query( array( 'who' => 'authors' ) );

Equals to:

$args = array(
	'meta_key'     => 'user_level',
	'meta_value'   => '0',
	'meta_compare' => '!=',
	'blog_id'      => 0
)
$user_query = new WP_User_Query( $args );

Total Count Parameter

  • count_total (boolean) - Whether to count the total number of users found. When true (default), the total number of results for the query can be retrieved using the get_total() method. If you don't need the total number of results, set this to false.

Has Published Posts Parameter

  • has_published_posts (boolean / array) - Pass an array of post types to filter results to users who have published posts in those post types. true is an alias for all public post types. Default is null. Since Version 4.3.

Return Fields Parameter

Set return values.

  • fields (string|array) - Which fields to return. Defaults to all.
    • 'ID' - Return an array of user id's.
    • 'display_name' - Return an array of user display names.
    • 'login' / 'user_login' - Return an array of user login names.
    • 'nicename' / 'user_nicename' - Return an array of user nicenames.
    • 'email' / 'user_email' - Return an array of user emails.
    • 'url' / 'user_url' - Return an array of user urls.
    • 'registered' / 'user_registered' - Return an array of user registered dates.
    • 'all (default) or all_with_meta' - Returns an array of WP_User objects. Must pass an array to subset fields returned. *'all_with_meta' currently returns the same fields as 'all' which does not include user fields stored in wp_usermeta. You must create a second query to get the user meta fields by ID or use the __get PHP magic method to get the values of these fields.

Return an array of WP_User object

$user_query = new WP_User_Query( array( 'role' => 'editor', 'fields' => 'all' ) );

Return List all blog editors, return limited fields in resulting row objects:

$user_fields = array( 'user_login', 'user_nicename', 'user_email', 'user_url' );
$user_query = new WP_User_Query( array( 'role' => 'editor', 'fields' => $user_fields ) );

Return Values

(Array) 
An array of IDs, stdClass objects, or WP_User objects, depending on the value of the 'fields' parameter.
  • If 'fields' is set to 'all' (default), or 'all_with_meta', it will return an array of WP_User objects (does not include related user meta fields even with 'all_with_meta' set) .
  • If 'fields' is set to an array of wp_users table fields, it will return an array of stdClass objects with only those fields.
  • If 'fields' is set to any individual wp_users table field, an array of IDs will be returned.

Filters

  • found_users_query - Alters SQL 'SELECT FOUND_ROWS()' clause to the query that returns the count total.

Examples

Here is a working example if you want to search a user by first_name / last_name / description and the default search_columns.

// The search term
$search_term = 'Ross';

// WP_User_Query arguments
$args = array (
    'role'       => 'reporter',
    'order'      => 'ASC',
    'orderby'    => 'display_name',
    'search'     => '*' . esc_attr( $search_term ) . '*',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'first_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'last_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'description',
            'value'   => $search_term ,
            'compare' => 'LIKE'
        )
    )
);

// 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 through 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';
}

Change Log

  • 4.4.0:
    • Add paged, role__in, role__not_in Parameters
    • Update role Parameter to permit an array or comma-separated list of values
    • Update number Parameter to support querying for all users with using -1
  • 4.3.0:
    • Add has_published_posts Parameter
  • 4.2.0:
    • Add meta_value_num option to orderby Parameter
  • 4.1.0:
    • Add include option to orderby Parameter
  • 3.5.0:
    • Add $query_vars Property
    • Add get() Methods
    • Add set() Methods
    • Add meta_query Parameter

Source File

WP_User_Query is located in wp-includes/class-wp-user-query.php.

Resources

Related

See also index of Class Reference and index of Function Reference.