Make WordPress Core

Opened 5 months ago

Last modified 4 months ago

#53177 new defect (bug)

WP_User_Query does not accept fields as string except ID

Reported by: rilwis Owned by:
Milestone: 5.9 Priority: normal
Severity: normal Version: 4.4
Component: Users Keywords: has-patch needs-testing
Focuses: docs Cc:


The documentation says that:

(string|array) Which fields to return. Single or all fields (string), or array of fields. Accepts 'ID', 'display_name', 'user_login', 'user_nicename', 'user_email', 'user_url', 'user_registered'. Use 'all' for all fields and 'all_with_meta' to include meta fields. Default 'all'.


However, when passing any user field rather than 'ID', it always return IDs.

Looking inside the code, I found this:

if ( is_array( $qv['fields'] ) ) {
	$qv['fields'] = array_unique( $qv['fields'] );

	$this->query_fields = array();
	foreach ( $qv['fields'] as $field ) {
		$field                = 'ID' === $field ? 'ID' : sanitize_key( $field );
		$this->query_fields[] = "$wpdb->users.$field";
	$this->query_fields = implode( ',', $this->query_fields );
} elseif ( 'all' === $qv['fields'] ) {
	$this->query_fields = "$wpdb->users.*";
} else {
	$this->query_fields = "$wpdb->users.ID";


which explains the issue well.

Is that a bug or a missing feature?

Attachments (1)

53177.diff (615 bytes) - added by NomNom99 5 months ago.

Download all attachments as: .zip

Change History (6)

#1 @peterwilsoncc
5 months ago

  • Version changed from trunk to 4.4

Thanks for the report.

I think it's a bug and either WP_User_Query::fill_query_vars() or the if statement you highlight ought to ensure the fields value is an array. The if statement would probably need some re-ordering if the value were forced to an array.

In pseudo code:

$qv['fields'] = (array) $qv['fields'];

if ( in_array( 'all', $qv['fields'], true ) {
  // all fields
} elseif ( ! empty( $qv['fields'] ) {
  // Custom list of fields
} else {
  // ID

For now I've set the version to the introduction of WP_User_Query::fill_query_vars() but the issue may have been introduced/incorrectly documented earlier.

5 months ago

#2 @NomNom99
5 months ago

Issue occurs only when fields is not an array.
The bug was on line:

$this->query_fields = "$wpdb->users.ID";

where "ID" is hardcoded.
Added a patch.

This ticket was mentioned in PR #1251 on WordPress/wordpress-develop by Sidsector9.

5 months ago

  • Keywords has-patch added

#4 @desrosj
5 months ago

  • Summary changed from WP_User_Query doesn't not accept fields as string except ID to WP_User_Query does not accept fields as string except ID

#5 @JeffPaul
4 months ago

  • Keywords needs-testing added
  • Milestone changed from Awaiting Review to 5.9

Has patch, worth reviewing in 5.9 release cycle.

Note: See TracTickets for help on using tickets.