WordPress get user by meta data

Wordpress

Wordpress Problem Overview


How can I retrieve all users registered in my WordPress blog having a particular meta data?

For example I have made an option to add a custom meta data for every registering users having meta key as parent_id. If I want to list all users having parent_id as 2 , then how can I do this?

Wordpress Solutions


Solution 1 - Wordpress

Since WP v3.1 it's ridiculously easy to search for a user by his/her meta key.

Use the function

get_users($args)

(WP Documentation)

The function takes an array of parameters, in your case you need

get_users(array(
    'meta_key' => 'parent_id',
    'meta_value' => '42'
))

Solution 2 - Wordpress

Simple way how to get one user by his metadata is:

$user = reset(
 get_users(
  array(
   'meta_key' => $meta_key,
   'meta_value' => $meta_value,
   'number' => 1
  )
 )
);

Solution 3 - Wordpress

Here is how you can get users based on a custom role and multiple metadata keys,

$available_drivers = get_users(
            array(
                'role' => 'driver',
                'meta_query' => array(
                    array(
                        'key' => 'approved',
                        'value' => true,
                        'compare' => '=='
                    ),
                    array(
                        'key' => 'available',
                        'value' => true,
                        'compare' => '=='
                    )
                )
            )
        );

Explaining the above query, I want only those users who I assigned the role of driver, and they are approved and available. The approved and available are custom fields created using ACF as True/False fields.

If you have additional metadata to test, add another array element to the meta_query array.

Meanwhile checkout my open source at github.com/patrickingle

Solution 4 - Wordpress

Here is the codex page from Wordpress detailing how to use the get_users($arg); function.

It contains examples how how to build custom functions to fetch various parts of user data. You'll have to naturally build and make some of your own changes to get it how you want.

Additionally here is a link to a function somebody built that will fetch user data based on roles within wordpress. You can configure it in many different ways with some tweeking, but this will allow you to filter your results in a more powerful manner.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrashanthView Question on Stackoverflow
Solution 1 - WordpressanrootsView Answer on Stackoverflow
Solution 2 - WordpressOzzyCzechView Answer on Stackoverflow
Solution 3 - Wordpresspingle60View Answer on Stackoverflow
Solution 4 - WordpressJemView Answer on Stackoverflow