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 ( $qv['has_published_posts'] && $blog_id ) {
259 if ( true === $qv['has_published_posts'] ) {
260 $post_types = get_post_types( array( 'public' => true ) );
262 $post_types = (array) $qv['has_published_posts'];
265 foreach ( $post_types as &$post_type ) {
266 $post_type = $wpdb->prepare( '%s', $post_type );
269 $posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts';
270 $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 ) . " ) )";
274 $this->meta_query = new WP_Meta_Query();
275 $this->meta_query->parse_query_vars( $qv );
277 if ( isset( $qv['who'] ) && 'authors' == $qv['who'] && $blog_id ) {
279 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level',
284 // Prevent extra meta query.
285 $qv['blog_id'] = $blog_id = 0;
287 if ( empty( $this->meta_query->queries ) ) {
288 $this->meta_query->queries = array( $who_query );
290 // Append the cap query to the original queries and reparse the query.
291 $this->meta_query->queries = array(
293 array( $this->meta_query->queries, $who_query ),
297 $this->meta_query->parse_query_vars( $this->meta_query->queries );
301 if ( isset( $qv['role'] ) ) {
302 if ( is_array( $qv['role'] ) ) {
303 $roles = $qv['role'];
304 } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) {
305 $roles = array_map( 'trim', explode( ',', $qv['role'] ) );
310 if ( isset( $qv['role__in'] ) ) {
311 $role__in = (array) $qv['role__in'];
314 $role__not_in = array();
315 if ( isset( $qv['role__not_in'] ) ) {
316 $role__not_in = (array) $qv['role__not_in'];
319 if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) {
320 $role_queries = array();
322 $roles_clauses = array( 'relation' => 'AND' );
323 if ( ! empty( $roles ) ) {
324 foreach ( $roles as $role ) {
325 $roles_clauses[] = array(
326 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
327 'value' => '"' . $role . '"',
332 $role_queries[] = $roles_clauses;
335 $role__in_clauses = array( 'relation' => 'OR' );
336 if ( ! empty( $role__in ) ) {
337 foreach ( $role__in as $role ) {
338 $role__in_clauses[] = array(
339 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
340 'value' => '"' . $role . '"',
345 $role_queries[] = $role__in_clauses;
348 $role__not_in_clauses = array( 'relation' => 'AND' );
349 if ( ! empty( $role__not_in ) ) {
350 foreach ( $role__not_in as $role ) {
351 $role__not_in_clauses[] = array(
352 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
353 'value' => '"' . $role . '"',
354 'compare' => 'NOT LIKE',
358 $role_queries[] = $role__not_in_clauses;
361 // If there are no specific roles named, make sure the user is a member of the site.
362 if ( empty( $role_queries ) ) {
363 $role_queries[] = array(
364 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities',
365 'compare' => 'EXISTS',
369 // Specify that role queries should be joined with AND.
370 $role_queries['relation'] = 'AND';
372 if ( empty( $this->meta_query->queries ) ) {
373 $this->meta_query->queries = $role_queries;
375 // Append the cap query to the original queries and reparse the query.
376 $this->meta_query->queries = array(
378 array( $this->meta_query->queries, $role_queries ),
382 $this->meta_query->parse_query_vars( $this->meta_query->queries );
385 if ( ! empty( $this->meta_query->queries ) ) {
386 $clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this );
387 $this->query_from .= $clauses['join'];
388 $this->query_where .= $clauses['where'];
390 if ( $this->meta_query->has_or_relation() ) {
391 $this->query_fields = 'DISTINCT ' . $this->query_fields;
396 $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : '';
397 $order = $this->parse_order( $qv['order'] );
399 if ( empty( $qv['orderby'] ) ) {
400 // Default order is by 'user_login'.
401 $ordersby = array( 'user_login' => $order );
402 } elseif ( is_array( $qv['orderby'] ) ) {
403 $ordersby = $qv['orderby'];
405 // 'orderby' values may be a comma- or space-separated list.
406 $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] );
409 $orderby_array = array();
410 foreach ( $ordersby as $_key => $_value ) {
415 if ( is_int( $_key ) ) {
416 // Integer key means this is a flat array of 'orderby' fields.
420 // Non-integer key means this the key is the field and the value is ASC/DESC.
425 $parsed = $this->parse_orderby( $_orderby );
431 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
434 // If no valid clauses were found, order by user_login.
435 if ( empty( $orderby_array ) ) {
436 $orderby_array[] = "user_login $order";
439 $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array );
442 if ( isset( $qv['number'] ) && $qv['number'] > 0 ) {
443 if ( $qv['offset'] ) {
444 $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']);
446 $this->query_limit = $wpdb->prepare( "LIMIT %d, %d", $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] );
451 if ( isset( $qv['search'] ) )
452 $search = trim( $qv['search'] );
455 $leading_wild = ( ltrim($search, '*') != $search );
456 $trailing_wild = ( rtrim($search, '*') != $search );
457 if ( $leading_wild && $trailing_wild )
459 elseif ( $leading_wild )
461 elseif ( $trailing_wild )
466 $search = trim($search, '*');
468 $search_columns = array();
469 if ( $qv['search_columns'] )
470 $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) );
471 if ( ! $search_columns ) {
472 if ( false !== strpos( $search, '@') )
473 $search_columns = array('user_email');
474 elseif ( is_numeric($search) )
475 $search_columns = array('user_login', 'ID');
476 elseif ( preg_match('|^https?://|', $search) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) )
477 $search_columns = array('user_url');
479 $search_columns = array('user_login', 'user_url', 'user_email', 'user_nicename', 'display_name');
483 * Filters the columns to search in a WP_User_Query search.
485 * The default columns depend on the search term, and include 'user_email',
486 * 'user_login', 'ID', 'user_url', 'display_name', and 'user_nicename'.
490 * @param array $search_columns Array of column names to be searched.
491 * @param string $search Text being searched.
492 * @param WP_User_Query $this The current WP_User_Query instance.
494 $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this );
496 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild );
499 if ( ! empty( $include ) ) {
500 // Sanitized earlier.
501 $ids = implode( ',', $include );
502 $this->query_where .= " AND $wpdb->users.ID IN ($ids)";
503 } elseif ( ! empty( $qv['exclude'] ) ) {
504 $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) );
505 $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)";
508 // Date queries are allowed for the user_registered field.
509 if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) {
510 $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' );
511 $this->query_where .= $date_query->get_sql();
515 * Fires after the WP_User_Query has been parsed, and before
516 * the query is executed.
518 * The passed WP_User_Query object contains SQL parts formed
519 * from parsing the given query.
523 * @param WP_User_Query $this The current WP_User_Query instance,
524 * passed by reference.
526 do_action_ref_array( 'pre_user_query', array( &$this ) );
530 * Execute the query, with the current variables.
534 * @global wpdb $wpdb WordPress database abstraction object.
536 public function query() {
539 $qv =& $this->query_vars;
541 $this->request = "SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit";
543 if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) {
544 $this->results = $wpdb->get_results( $this->request );
546 $this->results = $wpdb->get_col( $this->request );
550 * Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance.
554 * @global wpdb $wpdb WordPress database abstraction object.
556 * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query.
558 if ( isset( $qv['count_total'] ) && $qv['count_total'] )
559 $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) );
561 if ( !$this->results )
564 if ( 'all_with_meta' == $qv['fields'] ) {
565 cache_users( $this->results );
568 foreach ( $this->results as $userid )
569 $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
572 } elseif ( 'all' == $qv['fields'] ) {
573 foreach ( $this->results as $key => $user ) {
574 $this->results[ $key ] = new WP_User( $user, '', $qv['blog_id'] );
580 * Retrieve query variable.
585 * @param string $query_var Query variable key.
588 public function get( $query_var ) {
589 if ( isset( $this->query_vars[$query_var] ) )
590 return $this->query_vars[$query_var];
596 * Set query variable.
601 * @param string $query_var Query variable key.
602 * @param mixed $value Query variable value.
604 public function set( $query_var, $value ) {
605 $this->query_vars[$query_var] = $value;
609 * Used internally to generate an SQL string for searching across multiple columns
614 * @global wpdb $wpdb WordPress database abstraction object.
616 * @param string $string
618 * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for single site.
619 * Single site allows leading and trailing wildcards, Network Admin only trailing.
622 protected function get_search_sql( $string, $cols, $wild = false ) {
626 $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : '';
627 $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : '';
628 $like = $leading_wild . $wpdb->esc_like( $string ) . $trailing_wild;
630 foreach ( $cols as $col ) {
631 if ( 'ID' == $col ) {
632 $searches[] = $wpdb->prepare( "$col = %s", $string );
634 $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
638 return ' AND (' . implode(' OR ', $searches) . ')';
642 * Return the list of users.
647 * @return array Array of results.
649 public function get_results() {
650 return $this->results;
654 * Return the total number of users for the current query.
659 * @return int Number of total users.
661 public function get_total() {
662 return $this->total_users;
666 * Parse and sanitize 'orderby' keys passed to the user query.
671 * @global wpdb $wpdb WordPress database abstraction object.
673 * @param string $orderby Alias for the field to order by.
674 * @return string Value to used in the ORDER clause, if `$orderby` is valid.
676 protected function parse_orderby( $orderby ) {
679 $meta_query_clauses = $this->meta_query->get_clauses();
682 if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ) ) ) {
683 $_orderby = 'user_' . $orderby;
684 } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ) ) ) {
685 $_orderby = $orderby;
686 } elseif ( 'name' == $orderby || 'display_name' == $orderby ) {
687 $_orderby = 'display_name';
688 } elseif ( 'post_count' == $orderby ) {
689 // todo: avoid the JOIN
690 $where = get_posts_by_author_sql( 'post' );
691 $this->query_from .= " LEFT OUTER JOIN (
692 SELECT post_author, COUNT(*) as post_count
696 ) p ON ({$wpdb->users}.ID = p.post_author)
698 $_orderby = 'post_count';
699 } elseif ( 'ID' == $orderby || 'id' == $orderby ) {
701 } elseif ( 'meta_value' == $orderby || $this->get( 'meta_key' ) == $orderby ) {
702 $_orderby = "$wpdb->usermeta.meta_value";
703 } elseif ( 'meta_value_num' == $orderby ) {
704 $_orderby = "$wpdb->usermeta.meta_value+0";
705 } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) {
706 $include = wp_parse_id_list( $this->query_vars['include'] );
707 $include_sql = implode( ',', $include );
708 $_orderby = "FIELD( $wpdb->users.ID, $include_sql )";
709 } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) {
710 $meta_clause = $meta_query_clauses[ $orderby ];
711 $_orderby = sprintf( "CAST(%s.meta_value AS %s)", esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
718 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
723 * @param string $order The 'order' query variable.
724 * @return string The sanitized 'order' query variable.
726 protected function parse_order( $order ) {
727 if ( ! is_string( $order ) || empty( $order ) ) {
731 if ( 'ASC' === strtoupper( $order ) ) {
739 * Make private properties readable for backward compatibility.
744 * @param string $name Property to get.
745 * @return mixed Property.
747 public function __get( $name ) {
748 if ( in_array( $name, $this->compat_fields ) ) {
754 * Make private properties settable for backward compatibility.
759 * @param string $name Property to check if set.
760 * @param mixed $value Property value.
761 * @return mixed Newly-set property.
763 public function __set( $name, $value ) {
764 if ( in_array( $name, $this->compat_fields ) ) {
765 return $this->$name = $value;
770 * Make private properties checkable for backward compatibility.
775 * @param string $name Property to check if set.
776 * @return bool Whether the property is set.
778 public function __isset( $name ) {
779 if ( in_array( $name, $this->compat_fields ) ) {
780 return isset( $this->$name );
785 * Make private properties un-settable for backward compatibility.
790 * @param string $name Property to unset.
792 public function __unset( $name ) {
793 if ( in_array( $name, $this->compat_fields ) ) {
794 unset( $this->$name );
799 * Make private/protected methods readable for backward compatibility.
804 * @param callable $name Method to call.
805 * @param array $arguments Arguments to pass when calling.
806 * @return mixed Return value of the callback, false otherwise.
808 public function __call( $name, $arguments ) {
809 if ( 'get_search_sql' === $name ) {
810 return call_user_func_array( array( $this, $name ), $arguments );