How to run WP_Query to retrieve attachments to posts only from a particular category?

I have a WP blog with a few pages and posts and several categories. I want to write a loop to retrieve images attached to the posts (not the pages) and only those from a specific category and it’s children. The category id is 60.

This is the WP_Query call:

$my_query = new WP_Query( array(
  'post_type' => 'attachment',
  'cat' => '60',
  'post_mime_type' =>'image',
  'posts_per_page' => $batch_size,
  'nopaging' => false,
  'post_status' => 'all',
  'post_parent' => null,
  'meta_key' => 'my_hash',
  'orderby' => 'meta_value'
) );

But I get nothing!

What am I doing wrong?

3 Answers
3

You’ll need to first grab the posts, then grab the attachments that are children of said posts.

$my_query = new WP_Query( array(
    'meta_key' => 'my_hash',
    'nopaging' => true,
    'orderby' => 'meta_value',
    'fields' => 'ids',
    'cat' => '60',
));

if ( $post_ids = $my_query->get_posts() ) {
    $post_ids = implode( ',', $post_ids );
    $atts_ids = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_parent IN($post_ids) AND post_type="attachment"" );   

    $my_query->query( array(
        'posts_per_page' => $batch_size,
        'post_mime_type' =>'image',
        'post_status' => 'all',
        'post_type' => 'attachment',
        'post__in' => $atts_ids,
    ));
}

Leave a Comment