Retrieves list of users matching criteria.
Description
See also
Parameters
$args
arrayoptional- Arguments to retrieve users. See WP_User_Query::prepare_query() for more information on accepted arguments.
Default:
array()
Source
function get_users( $args = array() ) {
$args = wp_parse_args( $args );
$args['count_total'] = false;
$user_search = new WP_User_Query( $args );
return (array) $user_search->get_results();
}
Changelog
Version | Description |
---|---|
3.1.0 | Introduced. |
Please note that if you search by `meta_value` and it ends up being `”` (an empty string), the query, which is really a wrap over the `WP_User_Query` class and hence this applies to other functions as well, ends up forfeiting the check for the `meta_value` and simply downgrades to searching by `meta_key` only.
Please be very careful when you have `meta_values` that are dynamic or that you can’t/don’t check for this exact case, if the list that you retrieve using this query is used for something important, you might end up with security holes.
“User input should be parsed”. Yes, but, user input should not be immediately `esc_html`’d or the like, escape at output, sanitize before queries and now that we know this, check for validity — but here lies the problem, we, as well as some people who’ve been with WP for 10+ years didn’t know about this behavior. A `preg_match` fixes it all, yes, but only if your assumptions are updated with this knowledge.
Additionally, this is not a case of “you just forgot to parse”, we parse everything that comes inside and had security audits on our core codebase pieces but just simply weren’t aware of this behavior and assumed we didn’t even need to parse.
I’ve opened a ticket about it if you’re interested in a PoC and how it affected us specifically: https://core.trac.wordpress.org/ticket/49641
An example of fetching users that match any one of an array of roles using
role__in
.An example using the ‘search’ field.
This example will find and display all users that have a user name, ID, email of “john”. You can also do wild card search by adding an * before or after your search query. For example, to search for all users that start with “jo”, you would pass something like “jo*”.
The results will be all users whose user names, IDs, or emails that start with “jo”. The * can be placed before or after your search query. When placed before, the results will be all users that end in your query.
A basic example to display all subscribers in an unordered list.
An example of querying by a specific field.
WP_User_Query now accepts fields options in WordPress 6.0
https://make.wordpress.org/core/2022/04/29/wp_user_query-now-accepts-fields-options-in-wordpress-6-0/
The default value of the
number
parameter is -1, which means it lists all the users. It can cause performance issues on larger sites, so it should be used with caution.