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:
$my_key_query_args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'meta_query' => array(
array(
'key' => 'my_key',
'value' => '1',
'compare' => '=',
'type' => 'BINARY'
)
)
);
$my_key_query = new WP_Query( $my_key_query_args );
Second, notice the added post_status
parameter of my array. By default attachments are added with a post status of “inherit,” but WP_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:
The default WP_Query sets 'post_status'=>'published'
, but attachments default to 'post_status'=>'inherit'
so you’ll need to set the status to 'inherit'
or 'any'
.