If I use get_posts()
like so I get a number of results with the value 1 for the my_key
meta_key:
$posts = get_posts(
array(
'post_type' => 'attachment',
'meta_key' => 'my_key',
'meta_value' => '1'
)
);
//this has a bunch of results as expected
print_r($posts);
However if I create a similar query with WP_Query I get an empty result array
$args = array(
'post_type' => 'attachment',
'meta_query' => array(
array(
'key' => 'my_key',
'value' => '1',
'compare' => '=',
'type' => 'BINARY'
)
)
);
$query = new WP_Query();
$results = $query->query($args);
//this is empty
print_r($results);
I have tried a few varieties of the meta_query array all with no luck. I am thinking that this might be a bug, but wanted to make sure I was not missing something first.
First, just pass your arguments to the constructor of
WP_Query
as this is both cleaner, and the way you’re supposed to do it according to the Codex documentation of the class.You should be constructing things like this:
Second, notice the added
post_status
parameter of my array. By default attachments are added with a post status of “inherit,” butWP_Query
will look for posts with the status of “published,” “draft,” or “pending.” (See the documentation of that parameter as well).So there’s no bug here, we just forgot to check the defaults for all parameters passed into the object.
There’s a note on the “attachment” option for the
post_type
parameter that calls out this requirement:I believe your problem is that you’re trying to use
WP_Query
likeget_posts()
. It seems quite possible that the query is working, but you just can’t see the results.WP_Query
returns a query object that you loop through like this:Also, note that I used $my_query. I’m a little fuzzy on this, but I believe $query may be a reserved variable from WordPress, and either way, it’s often better if you make that query a little-more human-readable (maybe event $attachment_meta_query or something).