Created
August 19, 2015 07:49
-
-
Save windyjonas/dd6fd56b77f0b7215b68 to your computer and use it in GitHub Desktop.
Full name search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Search users by first/last name in addition to the built-in nicename search | |
* @param string $wp_user_query User query | |
* @return string Modified user query | |
*/ | |
function ws_user_search_by_name( $wp_user_query ) { | |
if ( false === strpos( $wp_user_query->query_where, '@' ) && ! empty( $_GET['s'] ) ) { | |
global $wpdb; | |
$uids = array(); | |
// Remove markup and extra spaces from search string | |
$qstr = sanitize_text_field( $_GET['s'] ); | |
// Get user ids from users that match first name, last name or full name | |
$usermeta_affected_ids = $wpdb->get_results( "SELECT DISTINCT user_id, GROUP_CONCAT(meta_value SEPARATOR ' ') as full_name FROM $wpdb->usermeta WHERE (meta_key='first_name' OR meta_key='last_name') GROUP BY user_id HAVING full_name LIKE '%{$qstr}%'" ); | |
foreach ( $usermeta_affected_ids as $maf ) { | |
array_push( $uids, $maf->user_id ); | |
} | |
// Get user ids from users that match nicename | |
$users_affected_ids = $wpdb->get_results( "SELECT DISTINCT ID FROM $wpdb->users WHERE LOWER(user_nicename) LIKE '%{$qstr}%'" ); | |
foreach ( $users_affected_ids as $maf ) { | |
if ( ! in_array( $maf->ID, $uids ) ) { | |
array_push( $uids,$maf->ID ); | |
} | |
} | |
// Modify the original user query, | |
// replace search for nicename and instead use the array of user ids that we have collected | |
$id_string = implode( ',', $uids ); | |
if ( ! empty( $id_string ) ) { | |
$wp_user_query->query_where = str_replace( "user_nicename LIKE '%{$qstr}%'", "ID IN({$id_string})", $wp_user_query->query_where ); | |
$wp_user_query->query_where = str_replace( "user_nicename LIKE '{$qstr}'", "ID IN({$id_string})", $wp_user_query->query_where ); | |
} | |
} | |
return $wp_user_query; | |
} | |
add_action( 'pre_user_query', 'ws_user_search_by_name' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment