WordPress admin user search by name

When we search user from wordpress dashboard (Users > All Users) we can search with username and email address. But we can’t search with first name or last name or both. So, what if we want to use search by name? You can use the following code snippet for that.

You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution.

[php]
add_action(‘pre_user_query’,’alter_pre_user_query’);
function alter_pre_user_query($user_search) {
global $wpdb;
$vars = $user_search->query_vars;
if (!is_null($vars[‘search’])) {
$search = preg_replace(‘/^*/’,”,$vars[‘search’]);
$search = preg_replace(‘/*$/’,”,$search);
$user_search->query_from .= ” INNER JOIN {$wpdb->usermeta} m1 ON ” .
“{$wpdb->users}.ID=m1.user_id AND (m1.meta_key=’first_name’)”;
$user_search->query_from .= ” INNER JOIN {$wpdb->usermeta} m2 ON ” .
“{$wpdb->users}.ID=m2.user_id AND (m2.meta_key=’last_name’)”;
if (preg_match(‘/^byname:/’,$search)) {
$search = preg_replace(‘/^byname:/’,”,$search);
$user_search->query_orderby = ‘ ORDER BY UPPER(m2.meta_value), UPPER(m1.meta_value) ‘;
$user_search->query_vars[‘search’] = $search;
$user_search->query_where = str_replace(‘byname:’,”,$user_search->query_where);
}
$names = explode(‘ ‘,$search,2);
if(count($names) > 1){
$first_name = $names[0];
$last_name = $names[1];
$names_where = $wpdb->prepare(“m1.meta_value LIKE ‘%s’ OR m2.meta_value LIKE ‘%s’ OR (m1.meta_value LIKE ‘%s’ AND m2.meta_value LIKE ‘%s’)”, “%{$search}%”,”%$search%”,”%$first_name%”,”%$last_name%”);
}else{
$names_where = $wpdb->prepare(“m1.meta_value LIKE ‘%s’ OR m2.meta_value LIKE ‘%s’”, “%{$search}%”,”%$search%”);
}
$user_search->query_where = str_replace(‘WHERE 1=1 AND (‘,
“WHERE 1=1 AND ({$names_where} OR “,$user_search->query_where);
}
}
[/php]

You may also read:  WordPress: How to load all styles and scripts in footer

So, take your user search option in the next level. You can use this in your theme to give users more flexibility or develop a tiny plugin too :)

You may also like...

Leave a Reply

%d bloggers like this: