5

I want to query posts where meta value is empty. for example, I want to get these three posts, with no meta values: enter image description here

Already tried:

$args = array(
    'post_type'   => 'attachment',
    'posts_per_page' => 10,
    'paged'          => $paged,
    'meta_query'  => array(
        array(
            'key' => '_wp_attachment_image_alt',
            'value' => '',
            'compare' => 'LIKE'
        )
    )
);
$attachments = new WP_Query($args);

and:

$args = array(
    'post_type'   => 'attachment',
    'posts_per_page' => 10,
    'paged'          => $paged,
    'meta_query'  => array(
        array(
            'key' => '_wp_attachment_image_alt',
            'value' => null,
            'compare' => 'LIKE'
        )
    )
);

But it doesn't work..

Any idea how to solve this?

Thank you

2 Answers 2

4

I think you forgot about the inherit post status. The default one in WP_Query is publish.

You should also use = instead of LIKE, to avoid using LIKE '%%' in the SQL query.

So try to add this:

'post_status' => 'inherit'

and

'compare' => '='

into your query arguments, to match the empty _wp_attachment_image_alt string values.

2
  • Yep I forget the post_status, and also now it works with '='. Whats the difference between '=' and 'LIKE'? I though '=' is for ints and 'LIKE' is for strings..Thanks
    – Avishay
    Commented Oct 5, 2016 at 10:00
  • If you use LIKE in the meta query of WP_Query for e.g. the value 'test', then the generated SQL query will contain LIKE '%test%' where % is a wildcard. So in your case it was LIKE '%%', that gives all values. Note that the meta value column is of type longtext so any numbers there are stored as strings. @Avishay
    – birgire
    Commented Oct 5, 2016 at 10:14
-1
'meta_query' => array(
    array(
     'key' => '_wp_attachment_image_alt',
     'compare' => 'NOT EXISTS' // this should work...
    ),
)
1
  • 2
    It doesn't work, since the key is exists..
    – Avishay
    Commented Oct 5, 2016 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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