I think you have two issues that can be resolved in one go:
'search' => '*' . esc_attr( $search_term ) . '*',
- You don’t need the
'*'
s around the term. It looks like you’re trying to do a wildcard, but that’s what search already does by adding SQL ‘%’ around your term. Essentially, you end up searching for"%*{$search_term}*%"
, which is probably not what you want. esc_attr
should be unnecessary here. The WordPress database class used in your query will escape your input for you.- Using
search
in this context is creating a query like this:
SELECT ... FROM wp_users JOIN wp_usermeta ... WHERE (
(
meta_key = 'nickname' AND meta_value LIKE 'search term'
) OR
(
meta_key LIKE 'last_name'
...
)
AND
(
wp_users.ID LIKE 'search term'
OR
wp_users.user_login LIKE 'search term'
)
) -- END WHERE
which is also probably not what you want. In a WP_User_Query
, search
means “Search for user logins matching this query”, not “search for general user meta matching this query.”
So, try something like this:
// wp_user_query arguments
$args = array (
'role' => 'customer',
'order' => 'asc',
'orderby' => 'display_name',
'meta_query' => array(
'relation' => 'or',
array(
'key' => 'nickname',
'value' => $search_term,
'compare' => 'like'
),
array(
'key' => 'last_name',
'value' => $search_term,
'compare' => 'like'
),
array(
'key' => 'billing_phone',
'value' => $search_term,
'compare' => 'like'
)
)
);