wordpress user search firstname lastname and display name code

In wordpress admin users listing page, wordpress admin has user search with username and email but we cannot search via display name or first name and last name.

We can add firstname, lastname and display name in users search. You just need to add following code.

/*
 * functions will be applicable for only wordpress admin
 */
if (is_admin()) {
 /*
 * Modify the User Search in Admin to include firstname, lastname and display_name
 */
 add_action('pre_user_query', 'wpapi_pre_user_query');

function wpapi_pre_user_query($user_search) {
 //die();
 global $wpdb;
 // print_r($user_search);
 $vars = $user_search->query_vars;
 if (!is_null($vars['search'])) {
 /* For some reason, the search term is enclosed in asterisks.
 Remove them */
 $search = preg_replace('/^\*/', '', $vars['search']);
 $search = preg_replace('/\*$/', '', $search);
 //print_r($search);
 //search in display name
 if(!empty($search)){
 $user_search->query_where = substr(trim($user_search->query_where), 0, -1) . " OR display_name LIKE '%". $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')";
 $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);
 }
 return $user_search;
 }

}

wordpress user search firstname lastname and display name code

wordpress user search firstname lastname and display name code

6 Comments

Add a Comment

Your email address will not be published. Required fields are marked *