Search Users by First and Last Name
Makes the search box on the Users screen also find people by their first name, last name or full name, not just username and email.
Opens WPIDE on
Code
add_filter( 'users_list_table_query_args', function ( $args ) {
$term = isset( $args['search'] ) ? trim( $args['search'], '* ' ) : '';
if ( '' === $term ) {
return $args;
}
$parts = preg_split( '/\s+/', $term );
if ( count( $parts ) > 1 ) {
$meta = array(
'relation' => 'AND',
array( 'key' => 'first_name', 'value' => $parts[0], 'compare' => 'LIKE' ),
array( 'key' => 'last_name', 'value' => end( $parts ), 'compare' => 'LIKE' ),
);
} else {
$meta = array(
'relation' => 'OR',
array( 'key' => 'first_name', 'value' => $term, 'compare' => 'LIKE' ),
array( 'key' => 'last_name', 'value' => $term, 'compare' => 'LIKE' ),
);
}
$by_name = get_users( array( 'fields' => 'ID', 'number' => 200, 'meta_query' => $meta, 'count_total' => false ) );
if ( ! $by_name ) {
return $args;
}
$by_core = get_users( array( 'fields' => 'ID', 'number' => 200, 'search' => $args['search'], 'count_total' => false ) );
$args['include'] = array_map( 'intval', array_unique( array_merge( $by_core, $by_name ) ) );
unset( $args['search'] );
return $args;
} );
Notes
Matches up to 200 users by name per search, which is plenty for a search box.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.