WP_User_Query will not combine meta + normal search methods

They seems to work together, but note the AND part between the search part and the meta query part, in the generated SQL query. I wonder if you expected OR instead?

Here are the generated SQL queries, for the two cases you mentioned:

Search + Meta Query:

SELECT DISTINCT SQL_CALC_FOUND_ROWS wp_users.* 
    FROM wp_users 
    INNER JOIN wp_usermeta 
        ON ( wp_users.ID = wp_usermeta.user_id ) 
    WHERE 1=1 
        AND 
        ( 
            (
                    wp_usermeta.meta_key = 'first_name' 
                AND CAST(wp_usermeta.meta_value AS CHAR) LIKE '%Ross%' 
            ) 
            OR 
            ( 
                    wp_usermeta.meta_key = 'last_name' 
                AND CAST(wp_usermeta.meta_value AS CHAR) LIKE '%Ross%' 
            ) 
            OR 
            (   
                    wp_usermeta.meta_key = 'description' 
                AND CAST(wp_usermeta.meta_value AS CHAR) LIKE '%Ross%'
            )
        ) 
        AND 
        (
               user_login LIKE '%Ross%' 
            OR user_nicename LIKE '%Ross%'
        ) 
    ORDER BY display_name ASC ;

Only Search:

SELECT SQL_CALC_FOUND_ROWS wp_users.* 
    FROM wp_users 
    WHERE 1=1 
        AND 
        (
               user_login LIKE '%Ross%' 
            OR user_nicename LIKE '%Ross%'
        ) 
    ORDER BY display_name ASC ;

Core check:

In the core we have the WP_User_Query::get_search_sql() method returning an AND part:

return ' AND (' . implode(' OR ', $searches) . ')';

and similarly in the WP_Meta_Query::get_sql_clauses() method, we have an AND part:

$sql['where'] = ' AND ' . $sql['where'];

Leave a Comment