2

I'm trying to use WP_User_Query class to list all users basing on their specific meta fields.

When I use simple single-meta query, it works fine:

$q = new WP_User_Query( array(
        'role' => 'contributor',
        'fields' => 'all_with_meta',
        'meta_key'  => 'first_meta',
        'meta_value' => '2'
    ) );

but when I try to make combined two-field query and find users that have had filled second_meta meta field, the query lists all contributors (meta query is not working at all):

 $q = new WP_User_Query( array(
        'role' => 'contributor',
        'fields' => 'all',
        'meta_query' => array(
            'relation' => 'AND',
            0 => array( 
                'meta_key'  => 'first_meta',
                'meta_value' => '2'),
            1 => array(
                'meta_key' => 'second_meta',
                'meta_value' => '',
                'meta_compare' => '!='
            )
        )
    ) );

How can I make this combined meta query work?

Of course I'm trying to find all users that are contributors, have first_meta==2 AND second_meta is not empty

3

It looks like you're using wrong parameters, please try this instead (untested):

$q = new WP_User_Query( 
    array(
        'role'          => 'contributor',
        'meta_query'    => array(
            'relation'  => 'AND',
            array( 
                'key'     => 'first_meta',
                'value'   => '2',
            ),
            array(
                'key'     => 'second_meta',
                'value'   => '',
                'compare' => '!='
            )
        )
    ) 
);

where we've used the key, value and compare parameters within the meta_query array. I've also removed the 'fields' => 'all' part, because it's set by default.

  • Easy mistake, shame on me ;) Thanks for your help! – Gacek Oct 28 '14 at 20:17
  • Happens to the best of us, good you worked it out – birgire Oct 28 '14 at 20:27
  • @birgire how do i go with multiple user role using your code just check link:- stackoverflow.com/questions/33871458/… – Sanjay Nakate Nov 23 '15 at 14:42
  • Good question, wait for WordPress 4.4, that's just around the corner and use the new role__in attribute ;-) @SanjayNakate – birgire Nov 23 '15 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.