I would like to get the first audio file in the media library filtered by a custom field, but it always returns an empty set of posts. I know that I have to pass
'post_status' => 'inherit' and
'post_type' => 'attachment', but it doesn't change anything.
<?php // Arguments $args = array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'audio', 'meta_key' => 'my_meta_key', 'meta_value' => 'my_meta_value', 'posts_per_page' => 1 ); // Create the query $audio_files = new WP_Query( $args ); // Output var_dump( $audio_files ); // the number of found posts is always 0 ?>
So I tried to minimise it by letting away all the meta-key-stuff and searched for any attachment (as mentioned here)
<?php // Arguments $args = array( 'post_type' => 'attachment', 'post_status' => 'inherit' ); // or "any", but without effect // Create the query $any_files = new WP_Query( $args ); // Output var_dump( $any_files ); // same: the number of found posts is always 0 ?>
When I do
var_dump( $any_files );, the request does not contain the selected post-status' (which is strange):
["request"]=> string(237) "SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'attachment' AND ((wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future')) ORDER BY wp_posts.post_date DESC LIMIT 0, 10"
So I tried it the old-fashioned way by a custom SQL-statement:
<?php // Get row by custom SQL-statement $wpdb->get_row( 'SELECT * FROM ' . $wpdb->prefix . 'posts p, ' . $wpdb->prefix . 'postmeta m WHERE p.post_mime_type LIKE "audio/%" AND p.ID = m.post_ID AND m.meta_key = "my_meta_key" AND m.meta_value = "my_meta_value" ORDER BY p.post_date DESC' ); ?>
And tataaaa! I get my first audio file.
I know there are similar questions:
- Broken? WP_Query and “attachment” as a post type
- WP_Query not working as expected for attachments and custom meta_query
But neither of them helped me, even though they were treating quite the same topic.
What I am missing here? Why aren't the given status' not recognized? I would like to use
Solved it: Months ago, I added some default post_status' to the query in the
pre_get_posts action hook. Oh man! @Milo: Thanks for your hint!