3 * User API: WP_User_Query class
11 * Core class used for querying users.
15 * @see WP_User_Query::prepare_query() for information on accepted arguments.
20 * Query vars, after parsing
26 public $query_vars = array();
29 * List of found user ids
38 * Total number of found users for the current query
44 private $total_users = 0;
47 * Metadata query container.
53 public $meta_query = false;
56 * The SQL query used to fetch matching users.
64 private $compat_fields = array( 'results', 'total_users' );
70 public $query_orderby;
78 * @param null|string|array $query Optional. The query variables.
80 public function __construct( $query = null ) {
81 if ( ! empty( $query ) ) {
82 $this->prepare_query( $query );
88 * Fills in missing query variables with default values.
93 * @param array $args Query vars, as passed to `WP_User_Query`.
94 * @return array Complete query variables with undefined ones filled in with defaults.
96 public static function fill_query_vars( $args ) {
98 'blog_id' => $GLOBALS['blog_id'],
100 'role__in' => array(),
101 'role__not_in' => array(),
104 'meta_compare' => '',
105 'include' => array(),
106 'exclude' => array(),
108 'search_columns' => array(),
109 'orderby' => 'login',
114 'count_total' => true,
117 'has_published_posts' => null,
120 return wp_parse_args( $args, $defaults );
124 * Prepare the query variables.
127 * @since 4.1.0 Added the ability to order by the `include` value.
128 * @since 4.2.0 Added 'meta_value_num' support for `$orderby` parameter. Added multi-dimensional array syntax
129 * for `$orderby` parameter.
130 * @since 4.3.0 Added 'has_published_posts' parameter.
131 * @since 4.4.0 Added 'paged', 'role__in', and 'role__not_in' parameters. The 'role' parameter was updated to
132 * permit an array or comma-separated list of values. The 'number' parameter was updated to support
133 * querying for all users with using -1.
137 * @global wpdb $wpdb WordPress database abstraction object.
138 * @global int $blog_id
140 * @param string|array $query {
141 * Optional. Array or string of Query parameters.
143 * @type int $blog_id The site ID. Default is the current site.
144 * @type string|array $role An array or a comma-separated list of role names that users must match
145 * to be included in results. Note that this is an inclusive list: users
146 * must match *each* role. Default empty.
147 * @type array $role__in An array of role names. Matched users must have at least one of these
148 * roles. Default empty array.
149 * @type array $role__not_in An array of role names to exclude. Users matching one or more of these
150 * roles will not be included in results. Default empty array.
151 * @type string $meta_key User meta key. Default empty.
152 * @type string $meta_value User meta value. Default empty.
153 * @type string $meta_compare Comparison operator to test the `$meta_value`. Accepts '=', '!=',
154 * '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
155 * 'BETWEEN', 'NOT BETWEEN', 'EXISTS', 'NOT EXISTS', 'REGEXP',
156 * 'NOT REGEXP', or 'RLIKE'. Default '='.
157 * @type array $include An array of user IDs to include. Default empty array.
158 * @type array $exclude An array of user IDs to exclude. Default empty array.
159 * @type string $search Search keyword. Searches for possible string matches on columns.
160 * When `$search_columns` is left empty, it tries to determine which
161 * column to search in based on search string. Default empty.
162 * @type array $search_columns Array of column names to be searched. Accepts 'ID', 'login',
163 * 'nicename', 'email', 'url'. Default empty array.
164 * @type string|array $orderby Field(s) to sort the retrieved users by. May be a single value,
165 * an array of values, or a multi-dimensional array with fields as
166 * keys and orders ('ASC' or 'DESC') as values. Accepted values are
167 * 'ID', 'display_name' (or 'name'), 'include', 'user_login'
168 * (or 'login'), 'user_nicename' (or 'nicename'), 'user_email'
169 * (or 'email'), 'user_url' (or 'url'), 'user_registered'
170 * or 'registered'), 'post_count', 'meta_value', 'meta_value_num',
171 * the value of `$meta_key`, or an array key of `$meta_query`. To use
172 * 'meta_value' or 'meta_value_num', `$meta_key` must be also be
173 * defined. Default 'user_login'.
174 * @type string $order Designates ascending or descending order of users. Order values
175 * passed as part of an `$orderby` array take precedence over this
176 * parameter. Accepts 'ASC', 'DESC'. Default 'ASC'.
177 * @type int $offset Number of users to offset in retrieved results. Can be used in
178 * conjunction with pagination. Default 0.
179 * @type int $number Number of users to limit the query for. Can be used in
180 * conjunction with pagination. Value -1 (all) is supported, but
181 * should be used with caution on larger sites.
182 * Default empty (all users).
183 * @type int $paged When used with number, defines the page of results to return.
185 * @type bool $count_total Whether to count the total number of users found. If pagination
186 * is not needed, setting this to false can improve performance.
188 * @type string|array $fields Which fields to return. Single or all fields (string), or array
189 * of fields. Accepts 'ID', 'display_name', 'user_login',
190 * 'user_nicename', 'user_email', 'user_url', 'user_registered'.
191 * Use 'all' for all fields and 'all_with_meta' to include
192 * meta fields. Default 'all'.
193 * @type string $who Type of users to query. Accepts 'authors'.
194 * Default empty (all users).
195 * @type bool|array $has_published_posts Pass an array of post types to filter results to users who have
196 * published posts in those post types. `true` is an alias for all
200 public function prepare_query( $query = array() ) {
203 if ( empty( $this->query_vars ) || ! empty( $query ) ) {
204 $this->query_limit = null;
205 $this->query_vars = $this->fill_query_vars( $query );
209 * Fires before the WP_User_Query has been parsed.
211 * The passed WP_User_Query object contains the query variables, not
212 * yet passed into SQL.
216 * @param WP_User_Query $this The current WP_User_Query instance,
217 * passed by reference.
219 do_action( 'pre_get_users', $this );
221 // Ensure that query vars are filled after 'pre_get_users'.
222 $qv =& $this->query_vars;
223 $qv = $this->fill_query_vars( $qv );
225 if ( is_array( $qv['fields'] ) ) {
226 $qv['fields'] = array_unique( $qv['fields'] );
228 $this->query_fields = array();
229 foreach ( $qv['fields'] as $field ) {
230 $field = 'ID' === $field ? 'ID' : sanitize_key( $field );
231 $this->query_fields[] = "$wpdb->users.$field";
233 $this->query_fields = implode( ',', $this->query_fields );
234 } elseif ( 'all' == $qv['fields'] ) {
235 $this->query_fields = "$wpdb->users.*";
237 $this->query_fields = "$wpdb->users.ID";
240 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
241 $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields;
243 $this->query_from = "FROM $wpdb->users";
244 $this->query_where = "WHERE 1=1";
246 // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below.
247 if ( ! empty( $qv['include'] ) ) {
248 $include = wp_parse_id_list( $qv['include'] );
254 if ( isset( $qv['blog_id'] ) ) {
255 $blog_id = absint( $qv['blog_id'] );
258 if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
259 $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level';
260 $qv['meta_value'] = 0;
261 $qv['meta_compare'] = '!=';
262 $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query
265 if ( $qv['has_published_posts'] && $blog_id ) {
266 if ( true === $qv['has_published_posts'] ) {
267 $post_types = get_post_types( array( 'public' => true ) );
269 $post_types = (array) $qv['has_published_posts'];
272 foreach ( $post_types as &$post_type ) {
273 $post_type = $wpdb->prepare( '%s', $post_type );
276 $posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
277 $this->query_where .= " AND $wpdb->users.ID IN ( SELECT DISTINCT $posts_table.post_author FROM $posts_table WHERE $posts_table.post_status = 'publish' AND $posts_table.post_type IN ( " . join( ", ", $post_types ) . " ) )";
281 $this->meta_query = new WP_Meta_Query();
282 $this->meta_query->parse_query_vars( $qv );
285 if ( isset( $qv['role'] ) ) {
286 if ( is_array( $qv['role'] ) ) {
287 $roles = $qv['role'];
288 } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) {
289 $roles = array_map( 'trim', explode( ',', $qv['role'] ) );
294 if ( isset( $qv['role__in'] ) ) {
295 $role__in = (array) $qv['role__in'];
298 $role__not_in = array();
299 if ( isset( $qv['role__not_in'] ) ) {
300 $role__not_in = (array) $qv['role__not_in'];
303 if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
304 $role_queries = array();
306 $roles_clauses = array( 'relation' => 'AND' );
307 if ( ! empty( $roles ) ) {
308 foreach ( $roles as $role ) {
309 $roles_clauses[] = array(
310 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
311 'value' => '"' . $role . '"',
316 $role_queries[] = $roles_clauses;
319 $role__in_clauses = array( 'relation' => 'OR' );
320 if ( ! empty( $role__in ) ) {
321 foreach ( $role__in as $role ) {
322 $role__in_clauses[] = array(
323 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
324 'value' => '"' . $role . '"',
329 $role_queries[] = $role__in_clauses;
332 $role__not_in_clauses = array( 'relation' => 'AND' );
333 if ( ! empty( $role__not_in ) ) {
334 foreach ( $role__not_in as $role ) {
335 $role__not_in_clauses[] = array(
336 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
337 'value' => '"' . $role . '"',
338 'compare' => 'NOT LIKE',
342 $role_queries[] = $role__not_in_clauses;
345 // If there are no specific roles named, make sure the user is a member of the site.
346 if ( empty( $role_queries ) ) {
347 $role_queries[] = array(
348 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
349 'compare' => 'EXISTS',
353 // Specify that role queries should be joined with AND.
354 $role_queries['relation'] = 'AND';
356 if ( empty( $this->meta_query->queries ) ) {
357 $this->meta_query->queries = $role_queries;
359 // Append the cap query to the original queries and reparse the query.
360 $this->meta_query->queries = array(
362 array( $this->meta_query->queries, $role_queries ),
366 $this->meta_query->parse_query_vars( $this->meta_query->queries );
369 if ( ! empty( $this->meta_query->queries ) ) {
370 $clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
371 $this->query_from .= $clauses['join'];
372 $this->query_where .= $clauses['where'];
374 if ( $this->meta_query->has_or_relation() ) {
375 $this->query_fields = 'DISTINCT ' . $this->query_fields;
380 $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
381 $order = $this->parse_order( $qv['order'] );
383 if ( empty( $qv['orderby'] ) ) {
384 // Default order is by 'user_login'.
385 $ordersby = array( 'user_login' => $order );
386 } elseif ( is_array( $qv['orderby'] ) ) {
387 $ordersby = $qv['orderby'];
389 // 'orderby' values may be a comma- or space-separated list.
390 $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] );
393 $orderby_array = array();
394 foreach ( $ordersby as $_key => $_value ) {
399 if ( is_int( $_key ) ) {
400 // Integer key means this is a flat array of 'orderby' fields.
404 // Non-integer key means this the key is the field and the value is ASC/DESC.
409 $parsed = $this->parse_orderby( $_orderby );
415 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
418 // If no valid clauses were found, order by user_login.
419 if ( empty( $orderby_array ) ) {
420 $orderby_array[] = "user_login $order";
423 $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array );
426 if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
427 if ( $qv['offset'] ) {
428 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
430 $this->query_limit = $wpdb->prepare( "LIMIT %d, %d", $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
435 if ( isset( $qv['search'] ) )
436 $search = trim( $qv['search'] );
439 $leading_wild = ( ltrim($search, '*') != $search );
440 $trailing_wild = ( rtrim($search, '*') != $search );
441 if ( $leading_wild && $trailing_wild )
443 elseif ( $leading_wild )
445 elseif ( $trailing_wild )
450 $search = trim($search, '*');
452 $search_columns = array();
453 if ( $qv['search_columns'] )
454 $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
455 if ( ! $search_columns ) {
456 if ( false !== strpos( $search, '@') )
457 $search_columns = array('user_email');
458 elseif ( is_numeric($search) )
459 $search_columns = array('user_login', 'ID');
460 elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
461 $search_columns = array('user_url');
463 $search_columns = array('user_login', 'user_url', 'user_email', 'user_nicename', 'display_name');
467 * Filter the columns to search in a WP_User_Query search.
469 * The default columns depend on the search term, and include 'user_email',
470 * 'user_login', 'ID', 'user_url', 'display_name', and 'user_nicename'.
474 * @param array $search_columns Array of column names to be searched.
475 * @param string $search Text being searched.
476 * @param WP_User_Query $this The current WP_User_Query instance.
478 $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
480 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
483 if ( ! empty( $include ) ) {
484 // Sanitized earlier.
485 $ids = implode( ',', $include );
486 $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
487 } elseif ( ! empty( $qv['exclude'] ) ) {
488 $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
489 $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
492 // Date queries are allowed for the user_registered field.
493 if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
494 $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
495 $this->query_where .= $date_query->get_sql();
499 * Fires after the WP_User_Query has been parsed, and before
500 * the query is executed.
502 * The passed WP_User_Query object contains SQL parts formed
503 * from parsing the given query.
507 * @param WP_User_Query $this The current WP_User_Query instance,
508 * passed by reference.
510 do_action_ref_array( 'pre_user_query', array( &$this ) );
514 * Execute the query, with the current variables.
518 * @global wpdb $wpdb WordPress database abstraction object.
520 public function query() {
523 $qv =& $this->query_vars;
525 $this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
527 if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
528 $this->results = $wpdb->get_results( $this->request );
530 $this->results = $wpdb->get_col( $this->request );
534 * Filter SELECT FOUND_ROWS() query for the current WP_User_Query instance.
538 * @global wpdb $wpdb WordPress database abstraction object.
540 * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
542 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
543 $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
545 if ( !$this->results )
548 if ( 'all_with_meta' == $qv['fields'] ) {
549 cache_users( $this->results );
552 foreach ( $this->results as $userid )
553 $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
556 } elseif ( 'all' == $qv['fields'] ) {
557 foreach ( $this->results as $key => $user ) {
558 $this->results[ $key ] = new WP_User( $user, '', $qv['blog_id'] );
564 * Retrieve query variable.
569 * @param string $query_var Query variable key.
572 public function get( $query_var ) {
573 if ( isset( $this->query_vars[$query_var] ) )
574 return $this->query_vars[$query_var];
580 * Set query variable.
585 * @param string $query_var Query variable key.
586 * @param mixed $value Query variable value.
588 public function set( $query_var, $value ) {
589 $this->query_vars[$query_var] = $value;
593 * Used internally to generate an SQL string for searching across multiple columns
598 * @global wpdb $wpdb WordPress database abstraction object.
600 * @param string $string
602 * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for single site.
603 * Single site allows leading and trailing wildcards, Network Admin only trailing.
606 protected function get_search_sql( $string, $cols, $wild = false ) {
610 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
611 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
612 $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
614 foreach ( $cols as $col ) {
615 if ( 'ID' == $col ) {
616 $searches[] = $wpdb->prepare( "$col = %s", $string );
618 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
622 return ' AND (' . implode(' OR ', $searches) . ')';
626 * Return the list of users.
631 * @return array Array of results.
633 public function get_results() {
634 return $this->results;
638 * Return the total number of users for the current query.
643 * @return int Number of total users.
645 public function get_total() {
646 return $this->total_users;
650 * Parse and sanitize 'orderby' keys passed to the user query.
655 * @global wpdb $wpdb WordPress database abstraction object.
657 * @param string $orderby Alias for the field to order by.
658 * @return string Value to used in the ORDER clause, if `$orderby` is valid.
660 protected function parse_orderby( $orderby ) {
663 $meta_query_clauses = $this->meta_query->get_clauses();
666 if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ) ) ) {
667 $_orderby = 'user_' . $orderby;
668 } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ) ) ) {
669 $_orderby = $orderby;
670 } elseif ( 'name' == $orderby || 'display_name' == $orderby ) {
671 $_orderby = 'display_name';
672 } elseif ( 'post_count' == $orderby ) {
673 // todo: avoid the JOIN
674 $where = get_posts_by_author_sql( 'post' );
675 $this->query_from .= " LEFT OUTER JOIN (
676 SELECT post_author, COUNT(*) as post_count
680 ) p ON ({$wpdb->users}.ID = p.post_author)
682 $_orderby = 'post_count';
683 } elseif ( 'ID' == $orderby || 'id' == $orderby ) {
685 } elseif ( 'meta_value' == $orderby || $this->get( 'meta_key' ) == $orderby ) {
686 $_orderby = "$wpdb->usermeta.meta_value";
687 } elseif ( 'meta_value_num' == $orderby ) {
688 $_orderby = "$wpdb->usermeta.meta_value+0";
689 } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
690 $include = wp_parse_id_list( $this->query_vars['include'] );
691 $include_sql = implode( ',', $include );
692 $_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
693 } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
694 $meta_clause = $meta_query_clauses[ $orderby ];
695 $_orderby = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
702 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
707 * @param string $order The 'order' query variable.
708 * @return string The sanitized 'order' query variable.
710 protected function parse_order( $order ) {
711 if ( ! is_string( $order ) || empty( $order ) ) {
715 if ( 'ASC' === strtoupper( $order ) ) {
723 * Make private properties readable for backwards compatibility.
728 * @param string $name Property to get.
729 * @return mixed Property.
731 public function __get( $name ) {
732 if ( in_array( $name, $this->compat_fields ) ) {
738 * Make private properties settable for backwards compatibility.
743 * @param string $name Property to check if set.
744 * @param mixed $value Property value.
745 * @return mixed Newly-set property.
747 public function __set( $name, $value ) {
748 if ( in_array( $name, $this->compat_fields ) ) {
749 return $this->$name = $value;
754 * Make private properties checkable for backwards compatibility.
759 * @param string $name Property to check if set.
760 * @return bool Whether the property is set.
762 public function __isset( $name ) {
763 if ( in_array( $name, $this->compat_fields ) ) {
764 return isset( $this->$name );
769 * Make private properties un-settable for backwards compatibility.
774 * @param string $name Property to unset.
776 public function __unset( $name ) {
777 if ( in_array( $name, $this->compat_fields ) ) {
778 unset( $this->$name );
783 * Make private/protected methods readable for backwards compatibility.
788 * @param callable $name Method to call.
789 * @param array $arguments Arguments to pass when calling.
790 * @return mixed Return value of the callback, false otherwise.
792 public function __call( $name, $arguments ) {
793 if ( 'get_search_sql' === $name ) {
794 return call_user_func_array( array( $this, $name ), $arguments );