Opened 4 years ago
#49982 new defect (bug)
WP_User_Query returns duplicates if a user has multiple meta keys of the same name, unless "relation = OR" is included which adds DISTINCT
Reported by: | radgh | Owned by: | |
---|---|---|---|
Milestone: | Awaiting Review | Priority: | normal |
Severity: | minor | Version: | 5.4 |
Component: | Users | Keywords: | |
Focuses: | Cc: |
Description
Hi,
I ran into a bug that seems to be reproducible in core WP. It is possible that WP_User_Query returns duplicate results of users when they have multiple rows of matching metadata. I have a reproducible example.
Have a user with the following metadata. And yes, this is silly duplicate metadata to begin with but the same would go for matching multiple conditions with add_user_meta() in realistic usage.
user_id | meta_key | meta_value
1 | program_tdw | Yes
1 | program_tdw | Yes
1 | program_tdw_status | certified
1 | program_tdw_status | certified
Use the following very basic meta query to get the users:
<?php $query_args = array( 'meta_query' => array( 'relation' => 'AND', // Must have TDW program enabled, and TDW Status of Certified array( 'key' => 'program_tdw', 'value' => 'Yes', ), array( 'key' => 'program_tdw_status', 'value' => 'certified', ), ), ); $users = new WP_User_Query( $query_args );
Your results will include User ID 1 two times, or potentially more times depending on how many specific meta key matches they have.
An obvious fix is to use "DISTINCT" on the user id column that is returned, but there is no equivalent "posts_distinct" filter for WP_User_Query. There is currently a working hack to specify any "relation => OR" in the meta query.
With that in mind my fix is to do this just before the last line:
<?php $query_args['meta_query'] = array( 'relation' => 'OR', $query_args['meta_query'] );
Here is a related Stack Overflow question about the same topic from a few years ago: https://wordpress.stackexchange.com/questions/220307/user-appears-twice-in-a-wp-user-query
It is probably minor but may have unexpected effects, like in my situation it was sending emails to some users twice. Imagine how difficult that was to debug the cause :(