Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress get user by meta data

Tags:

wordpress

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?

like image 549
Prashanth Avatar asked May 24 '11 06:05

Prashanth


4 Answers

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'
))
like image 124
anroots Avatar answered Nov 14 '22 23:11

anroots


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
  )
 )
);
like image 21
OzzyCzech Avatar answered Nov 15 '22 01:11

OzzyCzech


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

like image 14
pingle60 Avatar answered Nov 15 '22 01:11

pingle60


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.

like image 4
Jem Avatar answered Nov 15 '22 01:11

Jem