Last active
July 17, 2018 18:08
-
-
Save fillipetech/92d3c7d33179012012196a5643b1ee81 to your computer and use it in GitHub Desktop.
Search Users by name and other fields #wp #users
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
| /** | |
| 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' ); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment