The pre_user_search WordPress action allows you to modify the user search query before it is executed.
Usage
add_action('pre_user_search', 'your_custom_function_name'); function your_custom_function_name($user_search) { // your custom code here }
Parameters
- $user_search (WP_User_Query) – The WP_User_Query instance that contains the search query.
More information
See WordPress Developer Resources: pre_user_search
Examples
Exclude administrators from user search results
This example modifies the search query to exclude users with the ‘administrator’ role.
add_action('pre_user_search', 'exclude_administrators_from_search'); function exclude_administrators_from_search($user_search) { global $wpdb; $user_search->query_where .= " AND {$wpdb->users}.ID NOT IN ( SELECT user_id FROM {$wpdb->usermeta} WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->prefix}capabilities' AND {$wpdb->usermeta}.meta_value LIKE '%administrator%' )"; }
Search for users by their display name
This example allows you to search for users by their display name.
add_action('pre_user_search', 'search_users_by_display_name'); function search_users_by_display_name($user_search) { $search_string = $user_search->get('search'); if (!empty($search_string)) { $search_string = trim($search_string, '*'); global $wpdb; $user_search->query_where = str_replace("user_login", "display_name", $user_search->query_where); } }
Search for users with a specific meta key and value
This example searches for users who have a specific meta key and value.
add_action('pre_user_search', 'search_users_by_meta_key_and_value'); function search_users_by_meta_key_and_value($user_search) { global $wpdb; $user_search->query_from .= " LEFT JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID={$wpdb->usermeta}.user_id"; $user_search->query_where .= " AND {$wpdb->usermeta}.meta_key='your_meta_key' AND {$wpdb->usermeta}.meta_value='your_meta_value'"; }
Exclude users with a specific email domain
This example excludes users with email addresses from a specific domain.
add_action('pre_user_search', 'exclude_users_with_specific_email_domain'); function exclude_users_with_specific_email_domain($user_search) { global $wpdb; $user_search->query_where .= " AND {$wpdb->users}.user_email NOT LIKE '%@example.com'"; }
Order user search results by a custom meta field
This example orders the user search results by a custom meta field.
add_action('pre_user_search', 'order_user_search_by_custom_meta_field'); function order_user_search_by_custom_meta_field($user_search) { global $wpdb; $user_search->query_from .= " LEFT JOIN {$wpdb->usermeta} custom_sort ON {$wpdb->users}.ID=custom_sort.user_id AND custom_sort.meta_key='your_custom_meta_key'"; $user_search->query_orderby = "ORDER BY custom_sort.meta_value " . $user_search->query_vars['order']; }