Users: Prime user meta in WP_User_Query class.

When querying 'fields' equal to 'all' using the `WP_User_Query` class, this returns an array of `WP_User` objects. A `WP_User` object requires user meta to be primed, as the user's role is stored in user meta. Ensure that all users meta is primed in a single request by calling the `cache_users` function when querying 'fields' equal to 'all'. Soft deprecate fields equal to `all_with_meta` as it now acts the same as 'fields' equal to 'all'.

Props Spacedmonkey, peterwilsoncc, mehulkaklotar, timothyblynjacobs, furi3r.
Fixes #55594.

git-svn-id: https://develop.svn.wordpress.org/trunk@53655 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Jonny Harris
2022-07-05 09:26:21 +00:00
parent b8ae106814
commit 2db7debe8a
2 changed files with 30 additions and 12 deletions

View File

@@ -235,8 +235,8 @@ class WP_User_Query {
* - 'user_status'
* - 'spam' (only available on multisite installs)
* - 'deleted' (only available on multisite installs)
* - 'all' for all fields
* - 'all_with_meta' to include meta fields.
* - 'all' for all fields and loads user meta.
* - 'all_with_meta' Deprecated. Use 'all'.
* Default 'all'.
* @type string $who Type of users to query. Accepts 'authors'.
* Default empty (all users).
@@ -310,9 +310,7 @@ class WP_User_Query {
$this->query_fields[] = "$wpdb->users.$field";
}
$this->query_fields = implode( ',', $this->query_fields );
} elseif ( 'all' === $qv['fields'] ) {
$this->query_fields = "$wpdb->users.*";
} elseif ( ! in_array( $qv['fields'], $allowed_fields, true ) ) {
} elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] || ! in_array( $qv['fields'], $allowed_fields, true ) ) {
$this->query_fields = "$wpdb->users.ID";
} else {
$field = 'id' === strtolower( $qv['fields'] ) ? 'ID' : sanitize_key( $qv['fields'] );
@@ -808,7 +806,7 @@ class WP_User_Query {
{$this->query_limit}
";
if ( is_array( $qv['fields'] ) || 'all' === $qv['fields'] ) {
if ( is_array( $qv['fields'] ) ) {
$this->results = $wpdb->get_results( $this->request );
} else {
$this->results = $wpdb->get_col( $this->request );
@@ -842,19 +840,19 @@ class WP_User_Query {
foreach ( $this->results as $result ) {
$result->id = $result->ID;
}
} elseif ( 'all_with_meta' === $qv['fields'] ) {
} elseif ( 'all_with_meta' === $qv['fields'] || 'all' === $qv['fields'] ) {
cache_users( $this->results );
$r = array();
foreach ( $this->results as $userid ) {
$r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
if ( 'all_with_meta' === $qv['fields'] ) {
$r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] );
} else {
$r[] = new WP_User( $userid, '', $qv['blog_id'] );
}
}
$this->results = $r;
} elseif ( 'all' === $qv['fields'] ) {
foreach ( $this->results as $key => $user ) {
$this->results[ $key ] = new WP_User( $user, '', $qv['blog_id'] );
}
}
}