Reputation: 1326
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
?>
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:
But neither of them helped me, even though they were treating quite the same topic.
What I am missing here? I would like to use WP_Query
.
Upvotes: 3
Views: 4744
Reputation: 1154
I just now had a similar problem. Removing the post_status parameter from the wp_query arguments solved this for me.
Upvotes: 0
Reputation: 443
you should use offset,orderby and order when you are using posts_per_page it should definitely work. here is your revised code
if posts_per_page is -1 then it will list all post so in that case offset is ignored but in all other case you should use.
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'offset' => $offset,
'post_mime_type' => 'audio',
'meta_key' => 'my_meta_key',
'orderby' =>'ID',
'order' => 'ASC',
'meta_value' => 'my_meta_value',
'posts_per_page' => 1 );
Upvotes: 0