Working with the WordPress user meta query

WordPress has a powerful user meta function that allows developers and plugins to store additional metadata about the registered users in the database. This meta information can be all sorts of different data and attributes that can be used for different purposes. In this tutorial we are going to learn how to use the WordPress user meta query to retrieve and segment your WordPress users based on particular meta key with certain data value.

For this we are going to use a PHP class for direct database search WordPress user meta query, the WP_User_Query. Although it may seem complex at first, once you know how it works it can be a very powerful tool. And that’s our goal today, to master the basic elements of the WordPress user meta query for searching the custom user meta data.

And although the coding path is great and it is important to know how things work in the background, we are also going to explore some other options. It’s possible to use plugins to greatly simplify our user search tasks, it works like the WordPress meta query, but it’s a much easier approach.

wordpress user meta query

Using custom fields in a WordPress User Query

In order to follow along, we advise you create a child theme. Querying users from the WordPress database works in the same way as querying posts. Now let’s get familiarized with the WP_User_Query class. Its inner workings are again very similar to the WordPress posts query, the WP_Query. This is its basic syntax:

//simplest possible use of the WP_User_Query class
$user_query = new WP_User_Query( $args );

Now it’s time to gather all users who have a custom user field set. Thus, you find all users with that value, which can be set by another plugin or the user himself.

//A lot of arguments can be passed
//Here we get all users with the "developer" occupation
$args  = array(
    'meta_key' => 'occupation', //any custom field name
    'meta_value' => 'developer' //the value to compare against
);

$user_query = new WP_User_Query( $args );

This will retrieve all the registered users that meet the specified criteria, in our case, we’re only wanting to pull users that have a occupation meta key with “developer” set as a value. This snippet is, in fact, a shorter version of this one:

$args  = array(
    'meta_key' => 'occupation',
    'meta_value' => 'developer',
    'meta_compare' => '=' // exact match only
);

$user_query = new WP_User_Query( $args );

There we can see the meta_compare  attribute. It is set to “=” by default, but there are a lot of different operations that you can perform with it. Thus, you can use these values:

  • ‘=’ / ‘!=’ – Exact match
  • ‘>’ / ‘>=’ / ‘<‘ / ‘<=’ – Greater than, greater than or equal to, smaller than, smaller than or equal to
  • ‘LIKE’ / ‘NOT LIKE’ – Finds partial matches for a content, inside of a string. Then, if you search for “web”, you get not just “web” but “web design” and “spiderweb” too
  • ‘IN’ / ‘NOT IN’ – Allows specifying multiple values to match
  • ‘BETWEEN’ / ‘NOT BETWEEN’ – Allows matching based on a range of values. For example, you can search for users with age between 20 and 30
  • ‘EXISTS’ / ‘NOT EXISTS’ – Just check if the meta value is set at all
  • ‘REGEXP’ / ‘RLIKE’ / ‘NOT REGEXP’ – Use regular expressions in your search (being RLIKE just another term for REGEXP)

Thus, you can not only find exact values for your custom fields but try to find values different, greater than, lower than, similar to or even use regular expressions. Following our example, we could find all users who are NOT developers with this code:

$args  = array(
    'meta_key' => 'occupation',
    'meta_value' => 'developer',
    'meta_compare' => '!=' // everything but the exact match
);

$user_query = new WP_User_Query( $args );

Additionally, we can combine more than one set of parameters. This is done using the meta_query  parameter and adding inside of it a relation. After that, we add each of our different parameters. For instance, we can find all developers who are from the USA and with more than 5 years of experience:

//we use the meta_query argument to load a set of rules
$args = array(
    'meta_query' => array(
        'relation' => 'AND', // Could be OR, default is AND
            array(
                'key'     => 'occupation',
                'value'   => 'developer',
                 'compare' => '='
            ),
            array(
                'key'     => 'billing_country',
                'value'   => 'United States',
                 'compare' => '='
            ),
            array(
                'key'     => 'experience',
                'value'   => '5',
                 'compare' => '>=' // greater than or equal to 5
            )
    )
);

$user_query = new WP_User_Query( $args );

From the snippet above, we can see how different search criteria can be combined. The possible relations we can use are AND and OR. If we set it to AND, our results are going to match ALL our rules. If we set OR our results are any item that matches ANY of our rules.

Furthermore, we can use some of the more “obscure” parameters for great results in our WordPress meta query search. Let’s check again the previous example. There we look for users with a “Developer” occupation. But if we have a user who is a “PHP Developer” we won’t see him as a result. In this case, we can use the LIKE operator:

$args = array(
    'meta_query' => array(
        'relation' => 'AND',
            array(
                'key'     => 'occupation',
                'value'   => 'developer',
                 'compare' => 'LIKE' // any value that contains developer
            ),
            array(
                'key'     => 'billing_country',
                'value'   => 'United States',
                 'compare' => '='
            ),
            array(
                'key'     => 'experience',
                'value'   => '5',
                 'compare' => '>='
            )
    )
);

$user_query = new WP_User_Query( $args );

Also, we may want to check value ranges. Let’s say that in our WordPress custom user fields we have hourly rates for developers. If we want to search for a value that is within our budget, we can try the BETWEEN comparison.

$args = array(
    'meta_query' => array(
        'relation' => 'AND',
            array(
                'key'     => 'occupation',
                'value'   => 'developer',
                 'compare' => 'LIKE'
            ),
            array(
                'key'     => 'rate',
                'value'   => array( 30, 60 ),
                'type'    => 'numeric',
                'compare' => 'BETWEEN' // any value within that range of 30-60
            )
    )
);

$user_query = new WP_User_Query( $args );

Transform your WordPress user data into actionable insights

Ordering by user meta

Often when we perform a WordPress user meta query we need the results in a certain order. The WP_User_Query has an orderby parameter that we can use it for custom fields as well.

$args  = array(
    'meta_key' => 'age', // required for the orderby parameter
    'orderby' => 'meta_value',
    'order' => 'DESC'
);

$user_query = new WP_User_Query( $args );

This code is going to work fine, and it loads our users ordered by their age.

Except when it doesn’t.

The problem here is that our orderby will only work when the meta value is present in our query. And this means that we can’t order users with no values set in their custom field.

Hence, if we need to load WordPress users ordered by custom fields including empty values, we need something else. One way to solve this is simply loading all users, then using the pre_user_query action to add some extra code to the default query. In this way, our code will load all users, then we load their custom fields and order them.

Here is how that code would look like:

function load_users_with_meta() {
    //add our function on top of the user_query
    add_action( 'pre_user_query', 'add_my_custom_queries' );
    
    //a simple WP_User_Query with the display name as the result
    $query = new WP_User_Query(
        array(
            'fields' => array( 'display_name' ) 
        )
    );
    
    //processing the WP_USER_QUERY
    $users = $query->get_results();
    
    //we need to remove the action so it doesn't mess up with the rest of the user queries
    remove_action( 'pre_user_query', 'add_my_custom_queries' ); 
    
    //let's output our users now
    print_r($users);
    
}

function add_my_custom_queries( $query ) {
    global $wpdb;
    
    //let's add the billing_coutry to our meta fields in our query
    $query->query_fields .= ', billing_country.meta_value';

    //now we add a left join to actually gather the billing country for our users
    $query->query_from .= " LEFT JOIN $wpdb->usermeta billing_country ON $wpdb->users.ID = ".
        "billing_country.user_id and billing_country.meta_key = 'billing_country'";
    
    //and the last step is ordering users based on the billing_country values, when present
    $query->query_orderby = ' ORDER BY billing_country.meta_value DESC';
}

// just a way to output our result, could be in other hooks or a direct call to the function
add_action( 'init', 'load_users_with_meta' );

This code is going to load all users with their display names. Please note that the main query doesn’t include any operations to order the users by the meta fields. Then WordPress is going to apply our extra SQL query. That query is going to load the custom fields for our users and order them based on the values. In our case, we’ve used the “billing_country” custom field, but you can use any field you want.

Adding and Updating User Meta Values

Adding and updating user meta in WordPress works in a same way as with the post meta system. There are two main functions that we can use for this: update_user_meta()  and get_user_meta() . The update_user_meta()  function works based on user ID and if the meta field for the user does not exist, it will be added.

Now let’s see a much easier approach.

Query users based on custom meta fields with Users Insights

It’s possible to use Users Insights to search and order users based on their user meta fields. In this way, you can overcome the limitations of a coding-only approach. For example, if you want to just change a search parameter, it’s much harder to do it in your code.

The first element of our search is our custom fields. Make sure you have mapped your custom user fields, and you are able to use them. Let’s revive our WordPress meta query searches with just a few clicks.

Our first scenario is simply filtering users based on their occupation. This can be done by using the Occupation filter. You can use the variations of that field to search for “contains”, “starts with”, “ends with” and others.

wordpress filter users by occupation

When it comes to combining filters, you can use them with the AND operator in Users Insights. Therefore, to find developers from the US with more than 5 years of experience you can try this:

WordPress query users based on different parameters, occupation, country, experience

Additionally, we can add upper and lower boundaries for a range search. Like what we’ve done to find developers and their hourly rates.

FIlter users based on occupation, and hourly rate range

Furthermore, it’s possible to export our users, in case we want to contact them. You can just click the export button.

Export WordPress users filtered

Now it’s time for one of the toughest challenges we saw today: ordering. As opposed to a lot of custom code, you can simply click on the column you want to order by. That’s going to order all users based on that criterion, including users who don’t have it.

Order users by custom fields, country

Adding and updating custom user meta data

The Custom Fields feature of Users Insights allows you to create and update your own user meta information without the need of writing code. It provides a seamless interface to register custom fields and update the fields data for each user. Also the custom fields data is  automatically added to the Users Insights filters, so you can filter your WordPress users by your custom fields data.

You can register custom user meta fields in the Custom Fields section of Users Insights:

Users Insights create custom fields

Once the custom fields are registered, you can preview and update the data for each user in the user profile section:

WordPress custom user fields in profile

You can edit each of the custom fields data by clicking on the Edit icon and depending on the data type you will get the option to add text, number, date or chose from a select field.

WordPress edit a select custom user field

Conclusion

Today we saw many ways to use the WordPress user query. We looked into different examples, as well as some more complex ways to filter your users. We identified the limitations of the WP_User_Query and some ways to work around it. Additionally, we walked through how Users Insights can be used for a very similar purpose.

We hope you enjoyed this article, and see you again next time!