Support » Developing with WordPress » Adding custom user meta to search field on Users page in WordPress

  • I have added a custom meta value to each user and I have also added it to a custom sortable column on the users.php screen but I am now trying to incorporate this custom meta value into the “Search Users” search box.

    I have tried this code but it completely broke the search box, even searching the standard fields showed no results.

    Any help would be appreciated.

    'company_name' is the name of my custom value
      add_filter( 'user_search_columns', 'search_company_column', 10, 3 );
        function search_company_column( $search_columns, $search, $wp_user_query ) {
            $search_columns[] = 'company_name';
            return $search_columns;
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz


    “user_search_columns” is only for user table searches. User meta is in a different table. Use the ‘pre_get_users’ action and set appropriate meta_key, meta_value, meta_compare arguments. Be sure to only apply your criteria for your user search or you will corrupt other user query operations. One way to do so is add the action callback just before you need it and have your callback remove itself from the action stack once it is done setting criteria.

    Thread Starter joeinc


    Thanks for the help, I am now using the below code but like you said it breaks the other build in user queries like by name and email address

    Here is the code

    function search_by_users_query($query)
        global $pagenow;
        if (is_admin() && 'users.php' == $pagenow) {
            //Remove trailing and starting empty spaces
            $the_search = trim($query->query_vars['search']);
            $the_search = trim($query->query_vars['search'], '*');
            $query->set('meta_key', 'company_name');
            $query->set('meta_value', $the_search);
            $query->set('meta_compare', 'LIKE');
            $query->set('search', '');
    add_action('pre_get_users', 'search_by_users_query', 20);
    Moderator bcworkz


    remove_action('pre_get_users', 'search_by_users_query', 20);
    within your search_by_users_query() callback so it does not effect future queries. There should be certain values set in $query you could check to ensure you are only altering the proper search query. For example, only set the meta query vars if $query->query_vars['search'] is set.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Adding custom user meta to search field on Users page in WordPress’ is closed to new replies.