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

1 Answer
1

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.

Leave a Reply

Your email address will not be published. Required fields are marked *