If you want to do a search in your WordPress users, or in Ultimate Member members, (which amounts to the same thing), you would think this can be easily done with a meta_query, or with the search query functionality that is built in into WordPress.

This is not the case! When creating some code doing this, I discovered that with a meta_query, a user searched by username doesn’t get found. Looking in the query that is created by WordPress, I noticed that WordPress only searches in the wp_user_meta table. The username is part of the wp_users table.

On the other hand, if you use the “search” query, WordPress only searches in the users table, so won’t find users by firstname or lastname.

To solve it, you have to combine the two. In the example below, the totalusers variable contains the list of users that matches the input $str on either username, user_nicename, user_email, firstname, or lastname. You can extend it at will of course.

//search usertable
$wp_user_query = new WP_User_Query(
    'search' => "*{$str}*",
    'search_columns' => array(

) );
 $users = $wp_user_query->get_results();

//search usermeta
 $wp_user_query2 = new WP_User_Query(
    'meta_query' => array(
    'relation' => 'OR',
        'key' => 'first_name',
        'value' => $str,
        'compare' => 'LIKE'
        'key' => 'last_name',
        'value' => $str,
        'compare' => 'LIKE'

$users2 = $wp_user_query2->get_results();

$totalusers_dup = array_merge($users,$users2);

$totalusers = array_unique($totalusers_dup, SORT_REGULAR);

5 Responses

    1. This code is meant to be part of the code that executes the searching. It’s not really meant to be used as stand alone solution. For example, if you have a plugin with user search capability, you could check if there’s a filter or action in that plugin where you can hook in and manipulate the search results. So I can’t really say where to put this: it depends on your use case.

      1. You are good for nothing. This doesn’t help if you don’t tell us where to put it. It’s like giving us a piece of a puzzle and saying “I don’t know where to put it but I bet it’s part of it”.

        1. Wow.

          Just quietly: if you can’t figure this out on your own, you really shouldn’t be attempting to edit your site’s code.

          And if there were people around who might have had the inclination to help you, the rudeness of your response has pretty much ensured that will never happen.

Leave a Reply

Your email address will not be published. Required fields are marked *