/**
Extend user search in wp-admin
include first_name, last_name and other fields in the search results
**/
add_action('pre_user_query','extend_user_search');
function extend_user_search( $user_query ){
// make sure that this code will be applied only for user search
if ( $user_query->query_vars['search'] ){
$search_query = trim( $user_query->query_vars['search'], '*' );
if ( $_REQUEST['s'] == $search_query ){
global $wpdb;
// let's search by users first name
$user_query->query_from .= " JOIN {$wpdb->usermeta} fname ON fname.user_id = {$wpdb->users}.ID AND fname.meta_key = 'first_name'";
$user_query->query_from .= " JOIN {$wpdb->usermeta} lname ON lname.user_id = {$wpdb->users}.ID AND lname.meta_key = 'last_name'";
// you can add here any meta key you want to search by
// $u_query->query_from .= " JOIN {$wpdb->usermeta} cstm ON cstm.user_id = {$wpdb->users}.ID AND cstm.meta_key = 'YOU CUSTOM meta_key'";
// let's search by all the post titles, the user has been published
//$u_query->query_from .= " JOIN {$wpdb->posts} psts ON psts.post_author = {$wpdb->users}.ID";
// what fields to include in the search
$search_by = array( 'user_login', 'user_email', 'fname.meta_value', 'lname.meta_value');
// apply to the query
$user_query->query_where = 'WHERE 1=1' . $user_query->get_search_sql( $search_query, $search_by, 'both' );
}
}
}