1

So far I have tried these three options and all 3 of them are not working.

Option 1

$options = array(
    'meta_key'     => 'first_name',
    'meta_value'   => '',
    'meta_compare' => '=',
);

$users = get_users( $options );

Option 2

$options = array(
    'meta_key'     => 'first_name',
    'meta_value'   => null,
    'meta_compare' => '=',
);

$users = get_users( $options );

Option 3

$options = array(
    'meta_query' => array(
        array(
            'key'     => 'first_name',
            'compare' => 'NOT EXISTS',
        ),
    )
);
$users = get_users( $options );
1

It looks like you're searching for the first_name meta keys with empty string meta values:

$options = array(
    'meta_query' => array(
        array(
            'key'     => 'first_name',
            'value'   => '',
            'compare' => '=',
        ),
    )
);
$users = get_users( $options );

that generates this kind of SQL query:

SELECT wp_users.* 
FROM wp_users 
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) 
WHERE 
    1=1 AND ( ( wp_usermeta.meta_key = 'first_name' AND wp_usermeta.meta_value = '' ) ) 
ORDER BY user_login ASC 

Note that

$options = array(
    'meta_key'     => 'first_name',
    'meta_value'   => '',
    'meta_compare' => '=',
);
$users = get_users( $options );

generates this kind of SQL query:

SELECT wp_users.* 
FROM wp_users 
INNER JOIN wp_usermeta ON ( wp_users.ID = wp_usermeta.user_id ) 
WHERE 1=1 AND ( wp_usermeta.meta_key = 'first_name' ) 
ORDER BY user_login ASC ;
  • If user has not first name meta in data base then it not come with this query – Jignesh Patel Jul 6 '17 at 11:50
  • true but I understand that OP is only searching for empty meta values, not non-existing ones, as the questions title says:: How to query users who have empty first_name? Otherwise +1 for your answer's suggestion if looking for empty meta value strings or non-existent meta keys @PatelJignes – birgire Jul 6 '17 at 12:04
  • 1
    I was looking only for users who have a row in wp_usermeta table but with empty value. This answer worked perfectly for me. – Sudar Jul 6 '17 at 15:29
5

Used below code. it return all data which has not first_name key in data base or which has empty first_name

$args = array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'first_name',
            'value' => '',
            'compare' => '=',
        ),
        array(
            'key' => 'first_name',
            'value' => '',
            'compare' => 'NOT EXISTS',
        ),
    )
);
$users = get_users( $args );
var_dump($users);exit;
  • I don't want to retrieve users who don't have the meta key, but anyways thanks for the answer. – Sudar Jul 6 '17 at 15:42

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.