| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * User API: WP_User_Query class 4 * 5 * @package WordPress 6 * @subpackage Users 7 * @since 4.4.0 8 */ 9 10 /** 11 * Core class used for querying users. 12 * 13 * @since 3.1.0 14 * 15 * @see WP_User_Query::prepare_query() for information on accepted arguments. 16 */ 17 #[AllowDynamicProperties] 18 class WP_User_Query { 19 20 /** 21 * Query vars, after parsing 22 * 23 * @since 3.5.0 24 * @var array 25 */ 26 public $query_vars = array(); 27 28 /** 29 * List of found user IDs. 30 * 31 * @since 3.1.0 32 * @var array 33 */ 34 private $results; 35 36 /** 37 * Total number of found users for the current query 38 * 39 * @since 3.1.0 40 * @var int 41 */ 42 private $total_users = 0; 43 44 /** 45 * Metadata query container. 46 * 47 * This is false until the query is run. 48 * 49 * @since 4.2.0 50 * @var WP_Meta_Query|false 51 */ 52 public $meta_query = false; 53 54 /** 55 * The SQL query used to fetch matching users. 56 * 57 * @since 4.4.0 58 * @var string 59 */ 60 public $request; 61 62 private $compat_fields = array( 'results', 'total_users' ); 63 64 // SQL clauses. 65 public $query_fields; 66 public $query_from; 67 public $query_where; 68 public $query_orderby; 69 public $query_limit; 70 71 /** 72 * Constructor. 73 * 74 * @since 3.1.0 75 * 76 * @param null|string|array $query Optional. The query variables. 77 * See WP_User_Query::prepare_query() for information on accepted arguments. 78 */ 79 public function __construct( $query = null ) { 80 if ( ! empty( $query ) ) { 81 $this->prepare_query( $query ); 82 $this->query(); 83 } 84 } 85 86 /** 87 * Fills in missing query variables with default values. 88 * 89 * @since 4.4.0 90 * 91 * @param string|array $args Query vars, as passed to `WP_User_Query`. 92 * @return array Complete query variables with undefined ones filled in with defaults. 93 */ 94 public static function fill_query_vars( $args ) { 95 $defaults = array( 96 'blog_id' => get_current_blog_id(), 97 'role' => '', 98 'role__in' => array(), 99 'role__not_in' => array(), 100 'capability' => '', 101 'capability__in' => array(), 102 'capability__not_in' => array(), 103 'meta_key' => '', 104 'meta_value' => '', 105 'meta_compare' => '', 106 'include' => array(), 107 'exclude' => array(), 108 'search' => '', 109 'search_columns' => array(), 110 'orderby' => 'login', 111 'order' => 'ASC', 112 'offset' => '', 113 'number' => '', 114 'paged' => 1, 115 'count_total' => true, 116 'fields' => 'all', 117 'who' => '', 118 'has_published_posts' => null, 119 'nicename' => '', 120 'nicename__in' => array(), 121 'nicename__not_in' => array(), 122 'login' => '', 123 'login__in' => array(), 124 'login__not_in' => array(), 125 'cache_results' => true, 126 ); 127 128 return wp_parse_args( $args, $defaults ); 129 } 130 131 /** 132 * Prepares the query variables. 133 * 134 * @since 3.1.0 135 * @since 4.1.0 Added the ability to order by the `include` value. 136 * @since 4.2.0 Added 'meta_value_num' support for `$orderby` parameter. Added multi-dimensional array syntax 137 * for `$orderby` parameter. 138 * @since 4.3.0 Added 'has_published_posts' parameter. 139 * @since 4.4.0 Added 'paged', 'role__in', and 'role__not_in' parameters. The 'role' parameter was updated to 140 * permit an array or comma-separated list of values. The 'number' parameter was updated to support 141 * querying for all users with using -1. 142 * @since 4.7.0 Added 'nicename', 'nicename__in', 'nicename__not_in', 'login', 'login__in', 143 * and 'login__not_in' parameters. 144 * @since 5.1.0 Introduced the 'meta_compare_key' parameter. 145 * @since 5.3.0 Introduced the 'meta_type_key' parameter. 146 * @since 5.9.0 Added 'capability', 'capability__in', and 'capability__not_in' parameters. 147 * Deprecated the 'who' parameter. 148 * @since 6.3.0 Added 'cache_results' parameter. 149 * 150 * @global wpdb $wpdb WordPress database abstraction object. 151 * @global WP_Roles $wp_roles WordPress role management object. 152 * 153 * @param string|array $query { 154 * Optional. Array or string of query parameters. 155 * 156 * @type int $blog_id The site ID. Default is the current site. 157 * @type string|string[] $role An array or a comma-separated list of role names that users 158 * must match to be included in results. Note that this is 159 * an inclusive list: users must match *each* role. Default empty. 160 * @type string[] $role__in An array of role names. Matched users must have at least one 161 * of these roles. Default empty array. 162 * @type string[] $role__not_in An array of role names to exclude. Users matching one or more 163 * of these roles will not be included in results. Default empty array. 164 * @type string|string[] $meta_key Meta key or keys to filter by. 165 * @type string|string[] $meta_value Meta value or values to filter by. 166 * @type string $meta_compare MySQL operator used for comparing the meta value. 167 * See WP_Meta_Query::__construct() for accepted values and default value. 168 * @type string $meta_compare_key MySQL operator used for comparing the meta key. 169 * See WP_Meta_Query::__construct() for accepted values and default value. 170 * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons. 171 * See WP_Meta_Query::__construct() for accepted values and default value. 172 * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons. 173 * See WP_Meta_Query::__construct() for accepted values and default value. 174 * @type array $meta_query An associative array of WP_Meta_Query arguments. 175 * See WP_Meta_Query::__construct() for accepted values. 176 * @type string|string[] $capability An array or a comma-separated list of capability names that users 177 * must match to be included in results. Note that this is 178 * an inclusive list: users must match *each* capability. 179 * Does NOT work for capabilities not in the database or filtered 180 * via {@see 'map_meta_cap'}. Default empty. 181 * @type string[] $capability__in An array of capability names. Matched users must have at least one 182 * of these capabilities. 183 * Does NOT work for capabilities not in the database or filtered 184 * via {@see 'map_meta_cap'}. Default empty array. 185 * @type string[] $capability__not_in An array of capability names to exclude. Users matching one or more 186 * of these capabilities will not be included in results. 187 * Does NOT work for capabilities not in the database or filtered 188 * via {@see 'map_meta_cap'}. Default empty array. 189 * @type int[] $include An array of user IDs to include. Default empty array. 190 * @type int[] $exclude An array of user IDs to exclude. Default empty array. 191 * @type string $search Search keyword. Searches for possible string matches on columns. 192 * When `$search_columns` is left empty, it tries to determine which 193 * column to search in based on search string. Default empty. 194 * @type string[] $search_columns Array of column names to be searched. Accepts 'ID', 'user_login', 195 * 'user_email', 'user_url', 'user_nicename', 'display_name'. 196 * Default empty array. 197 * @type string|array $orderby Field(s) to sort the retrieved users by. May be a single value, 198 * an array of values, or a multi-dimensional array with fields as 199 * keys and orders ('ASC' or 'DESC') as values. Accepted values are: 200 * - 'ID' 201 * - 'display_name' (or 'name') 202 * - 'include' 203 * - 'user_login' (or 'login') 204 * - 'login__in' 205 * - 'user_nicename' (or 'nicename') 206 * - 'nicename__in' 207 * - 'user_email' (or 'email') 208 * - 'user_url' (or 'url') 209 * - 'user_registered' (or 'registered') 210 * - 'post_count' 211 * - 'meta_value' 212 * - 'meta_value_num' 213 * - The value of `$meta_key` 214 * - An array key of `$meta_query` 215 * To use 'meta_value' or 'meta_value_num', `$meta_key` 216 * must be also be defined. Default 'user_login'. 217 * @type string $order Designates ascending or descending order of users. Order values 218 * passed as part of an `$orderby` array take precedence over this 219 * parameter. Accepts 'ASC', 'DESC'. Default 'ASC'. 220 * @type int $offset Number of users to offset in retrieved results. Can be used in 221 * conjunction with pagination. Default 0. 222 * @type int $number Number of users to limit the query for. Can be used in 223 * conjunction with pagination. Value -1 (all) is supported, but 224 * should be used with caution on larger sites. 225 * Default -1 (all users). 226 * @type int $paged When used with number, defines the page of results to return. 227 * Default 1. 228 * @type bool $count_total Whether to count the total number of users found. If pagination 229 * is not needed, setting this to false can improve performance. 230 * Default true. 231 * @type string|string[] $fields Which fields to return. Single or all fields (string), or array 232 * of fields. Accepts: 233 * - 'ID' 234 * - 'display_name' 235 * - 'user_login' 236 * - 'user_nicename' 237 * - 'user_email' 238 * - 'user_url' 239 * - 'user_registered' 240 * - 'user_pass' 241 * - 'user_activation_key' 242 * - 'user_status' 243 * - 'spam' (only available on multisite installs) 244 * - 'deleted' (only available on multisite installs) 245 * - 'all' for all fields and loads user meta. 246 * - 'all_with_meta' Deprecated. Use 'all'. 247 * Default 'all'. 248 * @type string $who Deprecated, use `$capability` instead. 249 * Type of users to query. Accepts 'authors'. 250 * Default empty (all users). 251 * @type bool|string[] $has_published_posts Pass an array of post types to filter results to users who have 252 * published posts in those post types. `true` is an alias for all 253 * public post types. 254 * @type string $nicename The user nicename. Default empty. 255 * @type string[] $nicename__in An array of nicenames to include. Users matching one of these 256 * nicenames will be included in results. Default empty array. 257 * @type string[] $nicename__not_in An array of nicenames to exclude. Users matching one of these 258 * nicenames will not be included in results. Default empty array. 259 * @type string $login The user login. Default empty. 260 * @type string[] $login__in An array of logins to include. Users matching one of these 261 * logins will be included in results. Default empty array. 262 * @type string[] $login__not_in An array of logins to exclude. Users matching one of these 263 * logins will not be included in results. Default empty array. 264 * @type bool $cache_results Whether to cache user information. Default true. 265 * } 266 */ 267 public function prepare_query( $query = array() ) { 268 global $wpdb, $wp_roles; 269 270 if ( empty( $this->query_vars ) || ! empty( $query ) ) { 271 $this->query_limit = null; 272 $this->query_vars = $this->fill_query_vars( $query ); 273 } 274 275 /** 276 * Fires before the WP_User_Query has been parsed. 277 * 278 * The passed WP_User_Query object contains the query variables, 279 * not yet passed into SQL. 280 * 281 * @since 4.0.0 282 * 283 * @param WP_User_Query $query Current instance of WP_User_Query (passed by reference). 284 */ 285 do_action_ref_array( 'pre_get_users', array( &$this ) ); 286 287 // Ensure that query vars are filled after 'pre_get_users'. 288 $qv =& $this->query_vars; 289 $qv = $this->fill_query_vars( $qv ); 290 291 $allowed_fields = array( 292 'id', 293 'user_login', 294 'user_pass', 295 'user_nicename', 296 'user_email', 297 'user_url', 298 'user_registered', 299 'user_activation_key', 300 'user_status', 301 'display_name', 302 ); 303 if ( is_multisite() ) { 304 $allowed_fields[] = 'spam'; 305 $allowed_fields[] = 'deleted'; 306 } 307 308 if ( is_array( $qv['fields'] ) ) { 309 $qv['fields'] = array_map( 'strtolower', $qv['fields'] ); 310 $qv['fields'] = array_intersect( array_unique( $qv['fields'] ), $allowed_fields ); 311 312 if ( empty( $qv['fields'] ) ) { 313 $qv['fields'] = array( 'id' ); 314 } 315 316 $this->query_fields = array(); 317 foreach ( $qv['fields'] as $field ) { 318 $field = 'id' === $field ? 'ID' : sanitize_key( $field ); 319 $this->query_fields[] = "$wpdb->users.$field"; 320 } 321 $this->query_fields = implode( ',', $this->query_fields ); 322 } elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] || ! in_array( $qv['fields'], $allowed_fields, true ) ) { 323 $this->query_fields = "$wpdb->users.ID"; 324 } else { 325 $field = 'id' === strtolower( $qv['fields'] ) ? 'ID' : sanitize_key( $qv['fields'] ); 326 $this->query_fields = "$wpdb->users.$field"; 327 } 328 329 if ( isset( $qv['count_total'] ) && $qv['count_total'] ) { 330 $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields; 331 } 332 333 $this->query_from = "FROM $wpdb->users"; 334 $this->query_where = 'WHERE 1=1'; 335 336 // Parse and sanitize 'include', for use by 'orderby' as well as 'include' below. 337 if ( ! empty( $qv['include'] ) ) { 338 $include = wp_parse_id_list( $qv['include'] ); 339 } else { 340 $include = false; 341 } 342 343 $blog_id = 0; 344 if ( isset( $qv['blog_id'] ) ) { 345 $blog_id = absint( $qv['blog_id'] ); 346 } 347 348 if ( $qv['has_published_posts'] && $blog_id ) { 349 if ( true === $qv['has_published_posts'] ) { 350 $post_types = get_post_types( array( 'public' => true ) ); 351 } else { 352 $post_types = (array) $qv['has_published_posts']; 353 } 354 355 foreach ( $post_types as &$post_type ) { 356 $post_type = $wpdb->prepare( '%s', $post_type ); 357 } 358 359 $posts_table = $wpdb->get_blog_prefix( $blog_id ) . 'posts'; 360 $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 ( " . implode( ', ', $post_types ) . ' ) )'; 361 } 362 363 // nicename 364 if ( '' !== $qv['nicename'] ) { 365 $this->query_where .= $wpdb->prepare( ' AND user_nicename = %s', $qv['nicename'] ); 366 } 367 368 if ( ! empty( $qv['nicename__in'] ) ) { 369 $sanitized_nicename__in = array_map( 'esc_sql', $qv['nicename__in'] ); 370 $nicename__in = implode( "','", $sanitized_nicename__in ); 371 $this->query_where .= " AND user_nicename IN ( '$nicename__in' )"; 372 } 373 374 if ( ! empty( $qv['nicename__not_in'] ) ) { 375 $sanitized_nicename__not_in = array_map( 'esc_sql', $qv['nicename__not_in'] ); 376 $nicename__not_in = implode( "','", $sanitized_nicename__not_in ); 377 $this->query_where .= " AND user_nicename NOT IN ( '$nicename__not_in' )"; 378 } 379 380 // login 381 if ( '' !== $qv['login'] ) { 382 $this->query_where .= $wpdb->prepare( ' AND user_login = %s', $qv['login'] ); 383 } 384 385 if ( ! empty( $qv['login__in'] ) ) { 386 $sanitized_login__in = array_map( 'esc_sql', $qv['login__in'] ); 387 $login__in = implode( "','", $sanitized_login__in ); 388 $this->query_where .= " AND user_login IN ( '$login__in' )"; 389 } 390 391 if ( ! empty( $qv['login__not_in'] ) ) { 392 $sanitized_login__not_in = array_map( 'esc_sql', $qv['login__not_in'] ); 393 $login__not_in = implode( "','", $sanitized_login__not_in ); 394 $this->query_where .= " AND user_login NOT IN ( '$login__not_in' )"; 395 } 396 397 // Meta query. 398 $this->meta_query = new WP_Meta_Query(); 399 $this->meta_query->parse_query_vars( $qv ); 400 401 if ( isset( $qv['who'] ) && 'authors' === $qv['who'] && $blog_id ) { 402 _deprecated_argument( 403 'WP_User_Query', 404 '5.9.0', 405 sprintf( 406 /* translators: 1: who, 2: capability */ 407 __( '%1$s is deprecated. Use %2$s instead.' ), 408 '<code>who</code>', 409 '<code>capability</code>' 410 ) 411 ); 412 413 $who_query = array( 414 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'user_level', 415 'value' => 0, 416 'compare' => '!=', 417 ); 418 419 // Prevent extra meta query. 420 $qv['blog_id'] = 0; 421 $blog_id = 0; 422 423 if ( empty( $this->meta_query->queries ) ) { 424 $this->meta_query->queries = array( $who_query ); 425 } else { 426 // Append the cap query to the original queries and reparse the query. 427 $this->meta_query->queries = array( 428 'relation' => 'AND', 429 array( $this->meta_query->queries, $who_query ), 430 ); 431 } 432 433 $this->meta_query->parse_query_vars( $this->meta_query->queries ); 434 } 435 436 // Roles. 437 $roles = array(); 438 if ( isset( $qv['role'] ) ) { 439 if ( is_array( $qv['role'] ) ) { 440 $roles = $qv['role']; 441 } elseif ( is_string( $qv['role'] ) && ! empty( $qv['role'] ) ) { 442 $roles = array_map( 'trim', explode( ',', $qv['role'] ) ); 443 } 444 } 445 446 $role__in = array(); 447 if ( isset( $qv['role__in'] ) ) { 448 $role__in = (array) $qv['role__in']; 449 } 450 451 $role__not_in = array(); 452 if ( isset( $qv['role__not_in'] ) ) { 453 $role__not_in = (array) $qv['role__not_in']; 454 } 455 456 // Capabilities. 457 $available_roles = array(); 458 459 if ( ! empty( $qv['capability'] ) || ! empty( $qv['capability__in'] ) || ! empty( $qv['capability__not_in'] ) ) { 460 $wp_roles->for_site( $blog_id ); 461 $available_roles = $wp_roles->roles; 462 } 463 464 $capabilities = array(); 465 if ( ! empty( $qv['capability'] ) ) { 466 if ( is_array( $qv['capability'] ) ) { 467 $capabilities = $qv['capability']; 468 } elseif ( is_string( $qv['capability'] ) ) { 469 $capabilities = array_map( 'trim', explode( ',', $qv['capability'] ) ); 470 } 471 } 472 473 $capability__in = array(); 474 if ( ! empty( $qv['capability__in'] ) ) { 475 $capability__in = (array) $qv['capability__in']; 476 } 477 478 $capability__not_in = array(); 479 if ( ! empty( $qv['capability__not_in'] ) ) { 480 $capability__not_in = (array) $qv['capability__not_in']; 481 } 482 483 // Keep track of all capabilities and the roles they're added on. 484 $caps_with_roles = array(); 485 486 foreach ( $available_roles as $role => $role_data ) { 487 $role_caps = array_keys( array_filter( $role_data['capabilities'] ) ); 488 489 foreach ( $capabilities as $cap ) { 490 if ( in_array( $cap, $role_caps, true ) ) { 491 $caps_with_roles[ $cap ][] = $role; 492 break; 493 } 494 } 495 496 foreach ( $capability__in as $cap ) { 497 if ( in_array( $cap, $role_caps, true ) ) { 498 $role__in[] = $role; 499 break; 500 } 501 } 502 503 foreach ( $capability__not_in as $cap ) { 504 if ( in_array( $cap, $role_caps, true ) ) { 505 $role__not_in[] = $role; 506 break; 507 } 508 } 509 } 510 511 $role__in = array_merge( $role__in, $capability__in ); 512 $role__not_in = array_merge( $role__not_in, $capability__not_in ); 513 514 $roles = array_unique( $roles ); 515 $role__in = array_unique( $role__in ); 516 $role__not_in = array_unique( $role__not_in ); 517 518 // Support querying by capabilities added directly to users. 519 if ( $blog_id && ! empty( $capabilities ) ) { 520 $capabilities_clauses = array( 'relation' => 'AND' ); 521 522 foreach ( $capabilities as $cap ) { 523 $clause = array( 'relation' => 'OR' ); 524 525 $clause[] = array( 526 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 527 'value' => '"' . $cap . '"', 528 'compare' => 'LIKE', 529 ); 530 531 if ( ! empty( $caps_with_roles[ $cap ] ) ) { 532 foreach ( $caps_with_roles[ $cap ] as $role ) { 533 $clause[] = array( 534 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 535 'value' => '"' . $role . '"', 536 'compare' => 'LIKE', 537 ); 538 } 539 } 540 541 $capabilities_clauses[] = $clause; 542 } 543 544 $role_queries[] = $capabilities_clauses; 545 546 if ( empty( $this->meta_query->queries ) ) { 547 $this->meta_query->queries[] = $capabilities_clauses; 548 } else { 549 // Append the cap query to the original queries and reparse the query. 550 $this->meta_query->queries = array( 551 'relation' => 'AND', 552 array( $this->meta_query->queries, array( $capabilities_clauses ) ), 553 ); 554 } 555 556 $this->meta_query->parse_query_vars( $this->meta_query->queries ); 557 } 558 559 if ( $blog_id && ( ! empty( $roles ) || ! empty( $role__in ) || ! empty( $role__not_in ) || is_multisite() ) ) { 560 $role_queries = array(); 561 562 $roles_clauses = array( 'relation' => 'AND' ); 563 if ( ! empty( $roles ) ) { 564 foreach ( $roles as $role ) { 565 $roles_clauses[] = array( 566 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 567 'value' => '"' . $role . '"', 568 'compare' => 'LIKE', 569 ); 570 } 571 572 $role_queries[] = $roles_clauses; 573 } 574 575 $role__in_clauses = array( 'relation' => 'OR' ); 576 if ( ! empty( $role__in ) ) { 577 foreach ( $role__in as $role ) { 578 $role__in_clauses[] = array( 579 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 580 'value' => '"' . $role . '"', 581 'compare' => 'LIKE', 582 ); 583 } 584 585 $role_queries[] = $role__in_clauses; 586 } 587 588 $role__not_in_clauses = array( 'relation' => 'AND' ); 589 if ( ! empty( $role__not_in ) ) { 590 foreach ( $role__not_in as $role ) { 591 $role__not_in_clauses[] = array( 592 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 593 'value' => '"' . $role . '"', 594 'compare' => 'NOT LIKE', 595 ); 596 } 597 598 $role_queries[] = $role__not_in_clauses; 599 } 600 601 // If there are no specific roles named, make sure the user is a member of the site. 602 if ( empty( $role_queries ) ) { 603 $role_queries[] = array( 604 'key' => $wpdb->get_blog_prefix( $blog_id ) . 'capabilities', 605 'compare' => 'EXISTS', 606 ); 607 } 608 609 // Specify that role queries should be joined with AND. 610 $role_queries['relation'] = 'AND'; 611 612 if ( empty( $this->meta_query->queries ) ) { 613 $this->meta_query->queries = $role_queries; 614 } else { 615 // Append the cap query to the original queries and reparse the query. 616 $this->meta_query->queries = array( 617 'relation' => 'AND', 618 array( $this->meta_query->queries, $role_queries ), 619 ); 620 } 621 622 $this->meta_query->parse_query_vars( $this->meta_query->queries ); 623 } 624 625 if ( ! empty( $this->meta_query->queries ) ) { 626 $clauses = $this->meta_query->get_sql( 'user', $wpdb->users, 'ID', $this ); 627 $this->query_from .= $clauses['join']; 628 $this->query_where .= $clauses['where']; 629 630 if ( $this->meta_query->has_or_relation() ) { 631 $this->query_fields = 'DISTINCT ' . $this->query_fields; 632 } 633 } 634 635 // Sorting. 636 $qv['order'] = isset( $qv['order'] ) ? strtoupper( $qv['order'] ) : ''; 637 $order = $this->parse_order( $qv['order'] ); 638 639 if ( empty( $qv['orderby'] ) ) { 640 // Default order is by 'user_login'. 641 $ordersby = array( 'user_login' => $order ); 642 } elseif ( is_array( $qv['orderby'] ) ) { 643 $ordersby = $qv['orderby']; 644 } else { 645 // 'orderby' values may be a comma- or space-separated list. 646 $ordersby = preg_split( '/[,\s]+/', $qv['orderby'] ); 647 } 648 649 $orderby_array = array(); 650 foreach ( $ordersby as $_key => $_value ) { 651 if ( ! $_value ) { 652 continue; 653 } 654 655 if ( is_int( $_key ) ) { 656 // Integer key means this is a flat array of 'orderby' fields. 657 $_orderby = $_value; 658 $_order = $order; 659 } else { 660 // Non-integer key means this the key is the field and the value is ASC/DESC. 661 $_orderby = $_key; 662 $_order = $_value; 663 } 664 665 $parsed = $this->parse_orderby( $_orderby ); 666 667 if ( ! $parsed ) { 668 continue; 669 } 670 671 if ( 'nicename__in' === $_orderby || 'login__in' === $_orderby ) { 672 $orderby_array[] = $parsed; 673 } else { 674 $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order ); 675 } 676 } 677 678 // If no valid clauses were found, order by user_login. 679 if ( empty( $orderby_array ) ) { 680 $orderby_array[] = "user_login $order"; 681 } 682 683 $this->query_orderby = 'ORDER BY ' . implode( ', ', $orderby_array ); 684 685 // Limit. 686 if ( isset( $qv['number'] ) && $qv['number'] > 0 ) { 687 if ( $qv['offset'] ) { 688 $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['offset'], $qv['number'] ); 689 } else { 690 $this->query_limit = $wpdb->prepare( 'LIMIT %d, %d', $qv['number'] * ( $qv['paged'] - 1 ), $qv['number'] ); 691 } 692 } 693 694 $search = ''; 695 if ( isset( $qv['search'] ) ) { 696 $search = trim( $qv['search'] ); 697 } 698 699 if ( $search ) { 700 $leading_wild = ( ltrim( $search, '*' ) !== $search ); 701 $trailing_wild = ( rtrim( $search, '*' ) !== $search ); 702 if ( $leading_wild && $trailing_wild ) { 703 $wild = 'both'; 704 } elseif ( $leading_wild ) { 705 $wild = 'leading'; 706 } elseif ( $trailing_wild ) { 707 $wild = 'trailing'; 708 } else { 709 $wild = false; 710 } 711 if ( $wild ) { 712 $search = trim( $search, '*' ); 713 } 714 715 $search_columns = array(); 716 if ( $qv['search_columns'] ) { 717 $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename', 'display_name' ) ); 718 } 719 if ( ! $search_columns ) { 720 if ( str_contains( $search, '@' ) ) { 721 $search_columns = array( 'user_email' ); 722 } elseif ( is_numeric( $search ) ) { 723 $search_columns = array( 'user_login', 'ID' ); 724 } elseif ( preg_match( '|^https?://|', $search ) && ! ( is_multisite() && wp_is_large_network( 'users' ) ) ) { 725 $search_columns = array( 'user_url' ); 726 } else { 727 $search_columns = array( 'user_login', 'user_url', 'user_email', 'user_nicename', 'display_name' ); 728 } 729 } 730 731 /** 732 * Filters the columns to search in a WP_User_Query search. 733 * 734 * The default columns depend on the search term, and include 'ID', 'user_login', 735 * 'user_email', 'user_url', 'user_nicename', and 'display_name'. 736 * 737 * @since 3.6.0 738 * 739 * @param string[] $search_columns Array of column names to be searched. 740 * @param string $search Text being searched. 741 * @param WP_User_Query $query The current WP_User_Query instance. 742 */ 743 $search_columns = apply_filters( 'user_search_columns', $search_columns, $search, $this ); 744 745 $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild ); 746 } 747 748 if ( ! empty( $include ) ) { 749 // Sanitized earlier. 750 $ids = implode( ',', $include ); 751 $this->query_where .= " AND $wpdb->users.ID IN ($ids)"; 752 } elseif ( ! empty( $qv['exclude'] ) ) { 753 $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) ); 754 $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)"; 755 } 756 757 // Date queries are allowed for the user_registered field. 758 if ( ! empty( $qv['date_query'] ) && is_array( $qv['date_query'] ) ) { 759 $date_query = new WP_Date_Query( $qv['date_query'], 'user_registered' ); 760 $this->query_where .= $date_query->get_sql(); 761 } 762 763 /** 764 * Fires after the WP_User_Query has been parsed, and before 765 * the query is executed. 766 * 767 * The passed WP_User_Query object contains SQL parts formed 768 * from parsing the given query. 769 * 770 * @since 3.1.0 771 * 772 * @param WP_User_Query $query Current instance of WP_User_Query (passed by reference). 773 */ 774 do_action_ref_array( 'pre_user_query', array( &$this ) ); 775 } 776 777 /** 778 * Executes the query, with the current variables. 779 * 780 * @since 3.1.0 781 * 782 * @global wpdb $wpdb WordPress database abstraction object. 783 */ 784 public function query() { 785 global $wpdb; 786 787 if ( ! did_action( 'plugins_loaded' ) ) { 788 _doing_it_wrong( 789 'WP_User_Query::query', 790 sprintf( 791 /* translators: %s: plugins_loaded */ 792 __( 'User queries should not be run before the %s hook.' ), 793 '<code>plugins_loaded</code>' 794 ), 795 '6.1.1' 796 ); 797 } 798 799 $qv =& $this->query_vars; 800 801 // Do not cache results if more than 3 fields are requested. 802 if ( is_array( $qv['fields'] ) && count( $qv['fields'] ) > 3 ) { 803 $qv['cache_results'] = false; 804 } 805 806 /** 807 * Filters the users array before the query takes place. 808 * 809 * Return a non-null value to bypass WordPress' default user queries. 810 * 811 * Filtering functions that require pagination information are encouraged to set 812 * the `total_users` property of the WP_User_Query object, passed to the filter 813 * by reference. If WP_User_Query does not perform a database query, it will not 814 * have enough information to generate these values itself. 815 * 816 * @since 5.1.0 817 * 818 * @param array|null $results Return an array of user data to short-circuit WP's user query 819 * or null to allow WP to run its normal queries. 820 * @param WP_User_Query $query The WP_User_Query instance (passed by reference). 821 */ 822 $this->results = apply_filters_ref_array( 'users_pre_query', array( null, &$this ) ); 823 824 if ( null === $this->results ) { 825 // Beginning of the string is on a new line to prevent leading whitespace. See https://core.trac.wordpress.org/ticket/56841. 826 $this->request = 827 "SELECT {$this->query_fields} 828 {$this->query_from} 829 {$this->query_where} 830 {$this->query_orderby} 831 {$this->query_limit}"; 832 $cache_value = false; 833 $cache_key = $this->generate_cache_key( $qv, $this->request ); 834 $cache_group = 'user-queries'; 835 $last_changed = $this->get_cache_last_changed( $qv ); 836 837 if ( $qv['cache_results'] ) { 838 $cache_value = wp_cache_get_salted( $cache_key, $cache_group, $last_changed ); 839 } 840 if ( false !== $cache_value ) { 841 $this->results = $cache_value['user_data']; 842 $this->total_users = $cache_value['total_users']; 843 } else { 844 845 if ( is_array( $qv['fields'] ) ) { 846 $this->results = $wpdb->get_results( $this->request ); 847 } else { 848 $this->results = $wpdb->get_col( $this->request ); 849 } 850 851 if ( isset( $qv['count_total'] ) && $qv['count_total'] ) { 852 /** 853 * Filters SELECT FOUND_ROWS() query for the current WP_User_Query instance. 854 * 855 * @since 3.2.0 856 * @since 5.1.0 Added the `$query` parameter. 857 * 858 * @global wpdb $wpdb WordPress database abstraction object. 859 * 860 * @param string $sql The SELECT FOUND_ROWS() query for the current WP_User_Query. 861 * @param WP_User_Query $query The current WP_User_Query instance. 862 */ 863 $found_users_query = apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()', $this ); 864 865 $this->total_users = (int) $wpdb->get_var( $found_users_query ); 866 } 867 868 if ( $qv['cache_results'] ) { 869 $cache_value = array( 870 'user_data' => $this->results, 871 'total_users' => $this->total_users, 872 ); 873 wp_cache_set_salted( $cache_key, $cache_value, $cache_group, $last_changed ); 874 } 875 } 876 } 877 878 if ( ! $this->results ) { 879 return; 880 } 881 if ( 882 is_array( $qv['fields'] ) && 883 isset( $this->results[0]->ID ) 884 ) { 885 foreach ( $this->results as $result ) { 886 $result->id = $result->ID; 887 } 888 } elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] ) { 889 if ( function_exists( 'cache_users' ) ) { 890 cache_users( $this->results ); 891 } 892 893 $r = array(); 894 foreach ( $this->results as $userid ) { 895 if ( 'all_with_meta' === $qv['fields'] ) { 896 $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] ); 897 } else { 898 $r[] = new WP_User( $userid, '', $qv['blog_id'] ); 899 } 900 } 901 902 $this->results = $r; 903 } 904 } 905 906 /** 907 * Retrieves query variable. 908 * 909 * @since 3.5.0 910 * 911 * @param string $query_var Query variable key. 912 * @return mixed 913 */ 914 public function get( $query_var ) { 915 return $this->query_vars[ $query_var ] ?? null; 916 } 917 918 /** 919 * Sets query variable. 920 * 921 * @since 3.5.0 922 * 923 * @param string $query_var Query variable key. 924 * @param mixed $value Query variable value. 925 */ 926 public function set( $query_var, $value ) { 927 $this->query_vars[ $query_var ] = $value; 928 } 929 930 /** 931 * Used internally to generate an SQL string for searching across multiple columns. 932 * 933 * @since 3.1.0 934 * 935 * @global wpdb $wpdb WordPress database abstraction object. 936 * 937 * @param string $search Search string. 938 * @param string[] $columns Array of columns to search. 939 * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for single site. 940 * Single site allows leading and trailing wildcards, Network Admin only trailing. 941 * @return string 942 */ 943 protected function get_search_sql( $search, $columns, $wild = false ) { 944 global $wpdb; 945 946 $searches = array(); 947 $leading_wild = ( 'leading' === $wild || 'both' === $wild ) ? '%' : ''; 948 $trailing_wild = ( 'trailing' === $wild || 'both' === $wild ) ? '%' : ''; 949 $like = $leading_wild . $wpdb->esc_like( $search ) . $trailing_wild; 950 951 foreach ( $columns as $column ) { 952 if ( 'ID' === $column ) { 953 $searches[] = $wpdb->prepare( "$column = %s", $search ); 954 } else { 955 $searches[] = $wpdb->prepare( "$column LIKE %s", $like ); 956 } 957 } 958 959 return ' AND (' . implode( ' OR ', $searches ) . ')'; 960 } 961 962 /** 963 * Returns the list of users. 964 * 965 * @since 3.1.0 966 * 967 * @return array<int, mixed> Array of results. Contains WP_User objects unless the 'fields' query var 968 * requested specific fields, in which case it contains the requested values. 969 */ 970 public function get_results() { 971 return $this->results; 972 } 973 974 /** 975 * Returns the total number of users for the current query. 976 * 977 * @since 3.1.0 978 * 979 * @return int Number of total users. 980 */ 981 public function get_total() { 982 return $this->total_users; 983 } 984 985 /** 986 * Parses and sanitizes 'orderby' keys passed to the user query. 987 * 988 * @since 4.2.0 989 * 990 * @global wpdb $wpdb WordPress database abstraction object. 991 * 992 * @param string $orderby Alias for the field to order by. 993 * @return string Value to used in the ORDER clause, if `$orderby` is valid. 994 */ 995 protected function parse_orderby( $orderby ) { 996 global $wpdb; 997 998 $meta_query_clauses = $this->meta_query->get_clauses(); 999 1000 $_orderby = ''; 1001 if ( in_array( $orderby, array( 'login', 'nicename', 'email', 'url', 'registered' ), true ) ) { 1002 $_orderby = 'user_' . $orderby; 1003 } elseif ( in_array( $orderby, array( 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered' ), true ) ) { 1004 $_orderby = $orderby; 1005 } elseif ( 'name' === $orderby || 'display_name' === $orderby ) { 1006 $_orderby = 'display_name'; 1007 } elseif ( 'post_count' === $orderby ) { 1008 // @todo Avoid the JOIN. 1009 $where = get_posts_by_author_sql( 'post' ); 1010 $this->query_from .= " LEFT OUTER JOIN ( 1011 SELECT post_author, COUNT(*) as post_count 1012 FROM $wpdb->posts 1013 $where 1014 GROUP BY post_author 1015 ) p ON ({$wpdb->users}.ID = p.post_author)"; 1016 $_orderby = 'post_count'; 1017 } elseif ( 'ID' === $orderby || 'id' === $orderby ) { 1018 $_orderby = 'ID'; 1019 } elseif ( 'meta_value' === $orderby || $this->get( 'meta_key' ) === $orderby ) { 1020 $_orderby = "$wpdb->usermeta.meta_value"; 1021 } elseif ( 'meta_value_num' === $orderby ) { 1022 $_orderby = "$wpdb->usermeta.meta_value+0"; 1023 } elseif ( 'include' === $orderby && ! empty( $this->query_vars['include'] ) ) { 1024 $include = wp_parse_id_list( $this->query_vars['include'] ); 1025 $include_sql = implode( ',', $include ); 1026 $_orderby = "FIELD( $wpdb->users.ID, $include_sql )"; 1027 } elseif ( 'nicename__in' === $orderby ) { 1028 $sanitized_nicename__in = array_map( 'esc_sql', $this->query_vars['nicename__in'] ); 1029 $nicename__in = implode( "','", $sanitized_nicename__in ); 1030 $_orderby = "FIELD( user_nicename, '$nicename__in' )"; 1031 } elseif ( 'login__in' === $orderby ) { 1032 $sanitized_login__in = array_map( 'esc_sql', $this->query_vars['login__in'] ); 1033 $login__in = implode( "','", $sanitized_login__in ); 1034 $_orderby = "FIELD( user_login, '$login__in' )"; 1035 } elseif ( isset( $meta_query_clauses[ $orderby ] ) ) { 1036 $meta_clause = $meta_query_clauses[ $orderby ]; 1037 $_orderby = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) ); 1038 } 1039 1040 return $_orderby; 1041 } 1042 1043 /** 1044 * Generate cache key. 1045 * 1046 * @since 6.3.0 1047 * @since 6.9.0 The `$args` parameter was deprecated and renamed to `$deprecated`. 1048 * 1049 * @global wpdb $wpdb WordPress database abstraction object. 1050 * 1051 * @param array $deprecated Unused. 1052 * @param string $sql SQL statement. 1053 * @return string Cache key. 1054 */ 1055 protected function generate_cache_key( array $deprecated, $sql ) { 1056 global $wpdb; 1057 1058 // Replace wpdb placeholder in the SQL statement used by the cache key. 1059 $sql = $wpdb->remove_placeholder_escape( $sql ); 1060 1061 $key = md5( $sql ); 1062 1063 return "get_users:$key"; 1064 } 1065 1066 /** 1067 * Retrieves the last changed cache timestamp for users and optionally posts. 1068 * 1069 * @since 6.9.0 1070 * 1071 * @param array $args Query arguments. 1072 * @return string[] The last changed timestamp string for the relevant cache groups. 1073 */ 1074 protected function get_cache_last_changed( array $args ) { 1075 $last_changed = (array) wp_cache_get_last_changed( 'users' ); 1076 1077 if ( empty( $args['orderby'] ) ) { 1078 // Default order is by 'user_login'. 1079 $ordersby = array( 'user_login' => '' ); 1080 } elseif ( is_array( $args['orderby'] ) ) { 1081 $ordersby = $args['orderby']; 1082 } else { 1083 // 'orderby' values may be a comma- or space-separated list. 1084 $ordersby = preg_split( '/[,\s]+/', $args['orderby'] ); 1085 } 1086 1087 $blog_id = 0; 1088 if ( isset( $args['blog_id'] ) ) { 1089 $blog_id = absint( $args['blog_id'] ); 1090 } 1091 1092 if ( $args['has_published_posts'] || in_array( 'post_count', $ordersby, true ) ) { 1093 $switch = $blog_id && get_current_blog_id() !== $blog_id; 1094 if ( $switch ) { 1095 switch_to_blog( $blog_id ); 1096 } 1097 1098 $last_changed[] = wp_cache_get_last_changed( 'posts' ); 1099 1100 if ( $switch ) { 1101 restore_current_blog(); 1102 } 1103 } 1104 1105 return $last_changed; 1106 } 1107 1108 /** 1109 * Parses an 'order' query variable and casts it to ASC or DESC as necessary. 1110 * 1111 * @since 4.2.0 1112 * 1113 * @param string $order The 'order' query variable. 1114 * @return string The sanitized 'order' query variable. 1115 */ 1116 protected function parse_order( $order ) { 1117 if ( ! is_string( $order ) || empty( $order ) ) { 1118 return 'DESC'; 1119 } 1120 1121 if ( 'ASC' === strtoupper( $order ) ) { 1122 return 'ASC'; 1123 } else { 1124 return 'DESC'; 1125 } 1126 } 1127 1128 /** 1129 * Makes private properties readable for backward compatibility. 1130 * 1131 * @since 4.0.0 1132 * @since 6.4.0 Getting a dynamic property is deprecated. 1133 * 1134 * @param string $name Property to get. 1135 * @return mixed Property. 1136 */ 1137 public function __get( $name ) { 1138 if ( in_array( $name, $this->compat_fields, true ) ) { 1139 return $this->$name; 1140 } 1141 1142 wp_trigger_error( 1143 __METHOD__, 1144 "The property `{$name}` is not declared. Getting a dynamic property is " . 1145 'deprecated since version 6.4.0! Instead, declare the property on the class.', 1146 E_USER_DEPRECATED 1147 ); 1148 return null; 1149 } 1150 1151 /** 1152 * Makes private properties settable for backward compatibility. 1153 * 1154 * @since 4.0.0 1155 * @since 6.4.0 Setting a dynamic property is deprecated. 1156 * 1157 * @param string $name Property to check if set. 1158 * @param mixed $value Property value. 1159 */ 1160 public function __set( $name, $value ) { 1161 if ( in_array( $name, $this->compat_fields, true ) ) { 1162 $this->$name = $value; 1163 return; 1164 } 1165 1166 wp_trigger_error( 1167 __METHOD__, 1168 "The property `{$name}` is not declared. Setting a dynamic property is " . 1169 'deprecated since version 6.4.0! Instead, declare the property on the class.', 1170 E_USER_DEPRECATED 1171 ); 1172 } 1173 1174 /** 1175 * Makes private properties checkable for backward compatibility. 1176 * 1177 * @since 4.0.0 1178 * @since 6.4.0 Checking a dynamic property is deprecated. 1179 * 1180 * @param string $name Property to check if set. 1181 * @return bool Whether the property is set. 1182 */ 1183 public function __isset( $name ) { 1184 if ( in_array( $name, $this->compat_fields, true ) ) { 1185 return isset( $this->$name ); 1186 } 1187 1188 wp_trigger_error( 1189 __METHOD__, 1190 "The property `{$name}` is not declared. Checking `isset()` on a dynamic property " . 1191 'is deprecated since version 6.4.0! Instead, declare the property on the class.', 1192 E_USER_DEPRECATED 1193 ); 1194 return false; 1195 } 1196 1197 /** 1198 * Makes private properties un-settable for backward compatibility. 1199 * 1200 * @since 4.0.0 1201 * @since 6.4.0 Unsetting a dynamic property is deprecated. 1202 * 1203 * @param string $name Property to unset. 1204 */ 1205 public function __unset( $name ) { 1206 if ( in_array( $name, $this->compat_fields, true ) ) { 1207 unset( $this->$name ); 1208 return; 1209 } 1210 1211 wp_trigger_error( 1212 __METHOD__, 1213 "A property `{$name}` is not declared. Unsetting a dynamic property is " . 1214 'deprecated since version 6.4.0! Instead, declare the property on the class.', 1215 E_USER_DEPRECATED 1216 ); 1217 } 1218 1219 /** 1220 * Makes private/protected methods readable for backward compatibility. 1221 * 1222 * @since 4.0.0 1223 * 1224 * @param string $name Method to call. 1225 * @param array $arguments Arguments to pass when calling. 1226 * @return mixed Return value of the callback, false otherwise. 1227 */ 1228 public function __call( $name, $arguments ) { 1229 if ( 'get_search_sql' === $name ) { 1230 return $this->get_search_sql( ...$arguments ); 1231 } 1232 return false; 1233 } 1234 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Sat Dec 5 08:20:02 2026 | Cross-referenced by PHPXref |