WordPress get user by meta data

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?

Related posts

Leave a Reply

4 comments

  1. 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'
    ))
    
  2. 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
      )
     )
    );
    
  3. 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

  4. 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.