WP_User_Query class explained

This article provides a detailed overview of the WP_User_Query class in WordPress. The WP_User_Query class is used in WordPress to retrieve and manage user data by providing a flexible way to query and filter user information based on specified parameters. In this article, we’ll explore its main functionalities, break down search parameter options, dissect essential methods, and guide you on how to handle the returned data.

wp user query

How to use the WP_User_Query class

Before we dive into the specifics, let’s see an example of how to use the WP_User_Query class.

The WP_User_Query class constructor accepts one parameter – an associative array of search arguments. These arguments allow searching users by various information stored in the WordPress database. In the following sections, we’ll cover the accepted arguments in more detail.

Here is an example of instantiating a query that searches users with a subscriber role.

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

To run the query and return the results, we can use the get_results() method. Once this method is called, an SQL database query is run to fetch the matched results:

$users = $user_query->get_results();

The get_results() method returns an array of the found users. Each user result is an instance of the WP_User class. If no users match the given criteria, an empty array is returned. That’s why it is recommended to verify the existence of results before proceeding with any operations to avoid errors in the code.

Here is a basic example of how to use the WP_User_Query class:

$user_query = new WP_User_Query( array( 'role' => 'subscriber' ) );
$users = $user_query->get_results();

if(!empty($users)){
  foreach ($users as $user){
    echo '<p>'.$user->user_login.'</p>';
  }
}else{
  echo '<p>No users found</p>';
}

Searching users by main attributes

The main user attributes are the columns that are stored in the wp_users database table, and they include:

  • ID – the user ID
  • user_login – the username
  • user_email – user email
  • display_name – user display name
  • user_nicename – use nice name

You can search by any of these attributes by using the search and search_columns attributes of the WP_User_Query class:

  • search (string) – this is the search string. By default, it will search for an exact match. However, the * wild card can be used for partial matches. For example:
    • "John" – will search columns whose value is exactly “John”
    • "John*" – will search columns whose value starts with “John”
    • "*John" – will search columns whose value ends with “John”
    • "*John*" – will search columns whose value contains “John”
  • search_columns (array) – an array of the database columns which will be searched. If not specified, it will search across multiple columns; however, it is recommended to specify the searched columns to avoid unexpected results.

Let’s see some examples now.

Unlock the Full Potential of Your WooCommerce Customer Data

Querying users by email

The following example shows how to search users by email – it is an exact match, meaning that only one user will be returned if found:

$user_query = new WP_User_Query( 
  array( 'search' => 'admin@example.com', 'search_columns' => array ('user_email') ) 
);

And here is an example of how to get all users whose email is from the example.com domain, i.e. their email ends with “@example.com”:

$user_query = new WP_User_Query(
  array( 'search' => '*@example.com', 'search_columns' => array ('user_email') )
);

Querying users by display name

The following example illustrates how to search users by their display name – in this case, the query will return all users whose display name contains “John”:

$user_query = new WP_User_Query(
  array( 'search' => '*John*', 'search_columns' => array ('display_name') )
);

Searching users across multiple columns

As mentioned above, you can also search users based on value across multiple columns. The following query will search for users whose username or email contains the string “john”.

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

User role parameters

The user role parameters allow you to query users based on the role that they belong to.

  • role (string|array) – allows specifying one or multiple roles that the user must belong to. When multiple roles are specified in an array, the matched users must belong to all roles.
  • role__in (array) – an array of role names, matched users must belong to at least one of the specified roles.
  • role__not_in (array) – allows excluding users by role. Results will not include users who match one or more of these roles.

Now let’s see some examples:

Querying users by a role

The following query will return all users who have a Subscriber role:

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

Searching users by multiple roles

The following query will return all users who have a Subscriber AND a Customer role:

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

And if you want to find all users who have a Subscriber OR a Customer role, you can use the role__in parameter instead:

$user_query = new WP_User_Query( array( 'role__in' => array( 'Subscriber', 'Customer' ) ));

Excluding users by role

The following example excludes all users who have either the Subscriber or Customer role assigned:

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

Searching WordPress users by ID

The WP_User_Query class allows searching users by their ID using the following query parameters:

  • include (array) – allows specifying an array of user IDs to be included in the query results
  • exclude (array) – allows specifying an array of user IDs to be excluded in the query results

Using the include parameter

The following query will return a result containing users with the IDs 1, 2, and 3.

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

Using the exclude parameter

The following query will return a result containing all users except the ones with IDs 1, 2, and 3.

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

Date registered parameter

Querying WordPress users by date registered can be achieved using the date_query parameter. The date_query parameter works in the same way as the date_query parameter in the WP_Query class. It accepts an array of date conditions that can be met. Let’s see some examples:

Querying users who are registered on a given date

The following query will return all users who got registered on 4th January 2024:

$user_query = new WP_User_Query(
  array( 'date_query' => array( array( 'year' => 2024, 'month' => 1, 'day' => 4) ) )
);

As you can see, the date_query has one condition that specifies a year, month, and day. You can optionally omit any of these date parameters for a broader search. For example, to find all users who got registered in 2024 you can only set the year option:

$user_query = new WP_User_Query(
  array( 'date_query' => array( array( 'year' => 2024 ) ) )
);

Querying users who are registered between two dates

To find the users who were registered between two dates, you can set the date_query parameter as an associative array with before and after keys:

$user_query = new WP_User_Query( array( 'date_query' => array(
  'after' => array( 'year' => 2024, 'month' => 1, 'day' => 1),
  'before'=> array( 'year' => 2024, 'month' => 6, 'day' => 30),
  'inclusive' => true,
  'relation' => 'AND'
) ) );

This code snippet searches for users registered in the first half of 2024. Here is a breakdown of the date_query parameters:

  • after: sets a condition to find users registered after 1st January 2024
  • before: sets a condition to find users registered before 30 June 2024
  • inclusive: set to true, meaning that the conditional dates will be included, so users registered on 1st January 2024 and 30 June 2024 will be included
  • relation: set to AND, meaning that both before and after conditions must be met. If you set this option to OR, only one of the conditions must be met

User meta parameters

The WP_User_Query class provides flexible parameters allowing querying users by user meta fields (custom fields). There are two ways to query users by custom fields:

1. Querying users by a single meta condition

This is the simpler way to query users by custom fields. This approach is more suitable when searching users by only one meta field condition. The following parameters are available for querying:

  • meta_key – specifies the key of the meta field to search by
  • meta_value – specifies the value to search by
  • meta_compare – this is the search operator. The default operator is “=”, meaning an exact match is required. Other available operators are: ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘EXISTS’, ‘NOT EXISTS’, ‘REGEXP’, ‘NOT REGEXP’ and ‘RLIKE’

The following example queries all users whose “occupation” meta field is “Developer”:

$user_query = new WP_User_Query(
  array( 'meta_key' => 'occupation', 'meta_value' => 'Developer' )
);

and this query, on the other hand, will return users whose “occupation” meta field contains the string “Developer”:

new WP_User_Query(
  array( 'meta_key' => 'occupation', 'meta_value' => 'Developer', 'meta_compare' => 'LIKE' )
);

For querying numeric values, you can use numeric operators like ‘>’ and ‘<‘. The following snippet, for example, queries users who are older than 40:

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

2. Querying users by multiple meta conditions

When you need to query users by more than one custom field condition, you can use the meta_query parameter instead. The meta_query parameter allows you to build more advanced user meta queries.

Here is an example of querying users whose occupation custom field contains the text “developer” and whose country custom field is “France”:

$args = array(
  'meta_query' => array(
    'relation' => 'AND',
    array(
      'key' => 'occupation',
      'value' => 'developer',
      'compare' => 'LIKE'
    ),
    array(
      'key' => 'country',
      'value' => 'France',
      'compare' => '='
    )
  )
);

$user_query = new WP_User_Query( $args );

As you can see in the snippet above, we have added two meta conditions to the meta_query parameter. Each condition is an array supporting the following options:

  • key – the key of the meta field to query by
  • value – the search value
  • compare – the operator used for comparison. Similarly to the meta_compare option above, the supported operators are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘EXISTS’, ‘NOT EXISTS’, ‘REGEXP’, ‘NOT REGEXP’ and ‘RLIKE’.

We have also set a relation option to ‘AND’, meaning both conditions must be met. You can set this option to ‘OR’ if only one condition needs to be met.

To learn more about how to build more complex user meta queries, you can visit our detailed guide about working with WordPress user meta queries.

Querying users by first name and last name

The WP_User_Query doesn’t include an out-of-the-box parameter for first name and last name querying. However, in WordPress, the user first name and last name fields are stored as user meta. This means that we can use a meta query to search users by their name.

The first name is stored using the first_name key, which means that we can search users by their first name like this:

$user_query = new WP_User_Query( array( 'meta_key' => 'first_name', 'meta_value' => 'John' ) );

Similarly, to query users by their last name, we can use the last_name key:

$user_query = new WP_User_Query( array( 'meta_key' => 'last_name', 'meta_value' => 'Doe' ) );

Order Parameters

The WP_User_Query class supports the following parameters allowing to set the sorting order of the returned results:

  • orderby (string|array) – allows selecting a field or multiple fields to order the user list by. Supported options are:
    • ID – Order by user ID
    • display_name – Order by the user display name
    • include – Order by the included list of user_ids when the include parameter is used
    • login or user_login – Order by username (user login)
    • nicename or user_nicename – Order by user nickname
    • email or user_email – Order by user email
    • url or user_url – Order by user website
    • registered or user_registered – Order by date registered
    • post_count – Order by user post count
    • meta_value – Order by meta value – use with text-based values
    • meta_value_num – Order by meta value when the meta value contains numeric values. It is important to use this option when the meta field contains numeric values instead of meta_value. This is because meta_value uses alphabetical sorting, which means that it would sort numbers like this: 1, 2, 20, 3, 30, 4, while meta_value_num will sort the values numerically, e.g. 1, 2, 3, 4, 20, 30.
  • order (string) – allows to set order direction. The following options are supported:
    • ASC – ascending order, e.g., 1, 2, 3 for numbers and a, b, c for letters
    • DESC – descending order, e.g., 3, 2, 1 and c, b, a

Ordering users by a single field

The following examples illustrates ordering them by users by their username, in ascending order:

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

Ordering users by multiple fields

To order the users by multiple fields, simply pass the orderby fields as an array:

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

Querying and ordering users

The following snippet extends the example above, where we queried users by their age custom field. We have added additional orderby and order arguments. As you can see, the order by option is set to meta_value_num because the age field contains numeric values.

$args = array(
  'meta_key' => 'age',
  'meta_value' => '40',
  'meta_compare' => '>',
  'orderby' => 'meta_value_num',
  'order'=> 'ASC'
);
$user_query = new WP_User_Query( $args );

Pagination parameters

The pagination parameters that are supported by the WP_User_Query class allow you to load only a subset of the queried users. This is most helpful when you need to paginate the user results so that not all users are displayed at once.

The following pagination parameters are supported:

  • number (int) – sets the maximum number of users to return
  • paged (int) – number of page – returns the users that would show on the given page.
  • offset (int) – offsets the returned results, sets the number of users to pass over. Please note that setting the offset parameter overrides/ignores the paged parameter.

Here is an example of using the number and paged parameters:

$user_query = new WP_User_Query(
  array( 'orderby' => 'ID', 'order' => 'ASC', 'number' => 5, 'paged' => 2)
);

In this example, we sort the users by ID and load 5 users on page 2. This means that if we have 20 users with IDs from 1 to 20, it will return users with IDs 6, 7, 8, 9, and 10.

And here is an example of using the number and offset parameters:

$user_query = new WP_User_Query(
  array( 'orderby' => 'ID', 'order' => 'ASC', 'number' => 5, 'offset' => 2)
);

In this example, we set the offset option to 2. This means that the first 2 users will be skipped. For example, if we have 20 users with IDs from 1 to 20, the query will return users with IDs 3, 4, 5, 6, and 7.

Return fields parameter

The fields parameter allows you to specify which user fields to return in the result. By default each result is returned as WP_User object, however if you specify which fields to return, the result will depend on the how the fields parameter is used:

  • when the fields parameter is passed as a string containing a single field name, it will return an array containing the field values
  • when the fields parameter is passed as an array of fields, it will return an array of stdClass objects, each object containing only the specified fields

The advantage of using the fields parameter is that it can be memory efficient, especially when querying a large number of results. On the other hand, though, you lose the option to interact with the WP_User object and its methods. The available options for the fields parameter are:

  • ID
  • display_name
  • login / user_login
  • nicename / user_nicename
  • email / user_email
  • url / user_url
  • registered / user_registered
  • all (default) – returns a WP_User object

As an example, the following query:

$user_query = new WP_User_Query( array( 'fields' => 'user_login') );

will return an array of usernames, like this:

array('admin', 'johndoe', ...)

While this query, where the fields parameter is set as an array:

$user_query = new WP_User_Query( array( 'fields' => array('ID', 'user_login')) );

the result will be an array of stdClass objects, each with the ID and user_login properties only:

array(
  stdClass Object ( [ID] => 1 [user_login] => admin ),
  stdClass Object ( [ID] => 2 [user_login] => johndoe ),
  ...
)

Combining multiple parameters for more advanced queries

Now that we have covered all the main parameters let’s see how we can combine them into one query for more advanced user searches:

$args = array(
  'date_query' => array('after' => array('year' => 2023, 'month' => 1, 'day' => 1)),
  'role' => 'Subscriber',
  'search' => '*@example.com',
  'search_columns' => array ('user_email'),
  'meta_query' => array(
    'relation' => 'AND',
    array(
      'key' => 'occupation',
      'value' => 'developer',
      'compare' => 'LIKE'
    ),
    array(
      'key' => 'country',
      'value' => 'France',
      'compare' => '='
    )
  ),
  'orderby' => 'date_registered',
  'order' => 'ASC'
);
$user_query = new WP_User_Query($args);
$users = $user_query->get_results();

As you can see, this query includes several different user conditions, it queries all users who:

  • are registered after 1st Jan 2023
  • have a Subscriber role
  • have an email ending with @example.com
  • have an “occupation” meta field containing the text “developer”
  • have a “country” meta field with the value “France”

The returned users are sorted by their registration date in ascending order.

As you can see, the WP_User_Query class helps you do advanced user searches in WordPress using different parameters. However, the complexity of manual implementation may pose challenges in some cases. An alternative option is to use the Users Insights plugin. It does everything the WP_User_Query class does and more, all without a single line of code. Here is an example of querying the users using the same conditions as the example above:

WP_User_Query parameters in Users Insights

Users Insights also supports many additional features and conditions, allowing you to explore various user activity data, such as logins and page visits, geolocation, and data from all the supported 3rd party plugins, including WooCommerce. For more information, head over to the Features and Integrations page.

Advanced WordPress user searches

Conclusion

In this tutorial, we’ve covered the key aspects of the WP_User_Query class, detailing all the essential parameters and providing practical examples for creating advanced user queries. Now equipped with this information, you’re well-prepared to query and manage user data in your WordPress projects efficiently.