Searching the main table
Simply use WP_User_Query
with a search argument.
So if you want to search for example for a user with a keyword in his user_email
or similar columns from the {$wpdb->prefix}users
table, then you can do the following:
$users = new WP_User_Query( array(
'search' => '*'.esc_attr( $your_search_string ).'*',
'search_columns' => array(
'user_login',
'user_nicename',
'user_email',
'user_url',
),
) );
$users_found = $users->get_results();
Keep in mind that *
is a wildcard. So restricting for example the user_email
to a single domain would give you the following search string: *@example.com
.
The search
string has some "magic" features: The search_columns
defaults to...
user_email
if @
is present in the search
arg.
user_login
and ID
if the search
arg is numeric
user_url
if the search
string contains http://
or https://
- or ...
user_login
and user_nicename
if a string is present.
All those defaults are only set if no search_columns
argument was specified.
Searching the meta table
If you want to search by for example first_name
or last_name
, then you'll have to do a meta_query
as they're not part of the main table:
$search_string = esc_attr( trim( get_query_var('s') ) );
$users = new WP_User_Query( array(
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => $search_string,
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $search_string,
'compare' => 'LIKE'
)
)
) );
$users_found = $users->get_results();
Make sure you retrieve the right search string. Normally that would be get_query_var('s');
, but it could - depending on your form name/id
as well be something different that you might want to retrieve using $_GET['user_search']
for example. Make sure to properly esacpe it and remove unwanted white space from the beginning and end of the string.
Keep in mind that this is an array( array() )
as there's the relation
key. If you just want to have a single key searched, it might be easier to just go with the following:
$search_string = esc_attr( trim( get_query_var('s') ) );
$users = new WP_User_Query( array(
'meta_key' => 'first_name',
'meta_value' => $search_string,
'meta_compare' => 'LIKE',
) );
$users_found = $users->get_results();
Final query
The result might look close to the following:
$search_string = esc_attr( trim( get_query_var('s') ) );
$users = new WP_User_Query( array(
'search' => "*{$search_string}*",
'search_columns' => array(
'user_login',
'user_nicename',
'user_email',
'user_url',
),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'first_name',
'value' => $search_string,
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $search_string,
'compare' => 'LIKE'
)
)
) );
$users_found = $users->get_results();