Find attached images for one post type

I would like to query for images attached to ALL posts of certain custom post type (e.g. ‘gallery’).

I can’t see a way to do this by using only WP_Query. The workaround would be to query for all posts of a custom post type, then get the attachments and stuff everything together. But i don’t think that this would be a good solution, because you end up doing multiple queries for something that should be done in one.

Read More

Please help =)

Related posts

Leave a Reply

2 comments

  1. Try this code and replace custom-post with your custom post type.

    $query = new WP_Query( array( 'post_type' => 'custom-post', 'posts_per_page' => -1 ) );
    if( $query->have_posts() ){
        while($query->have_posts()){
            $query->the_post();
            $image_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'posts_per_page' => -1, 'post_parent' => get_the_ID() ) );
            while( $image_query->have_posts() ) {
                $image_query->the_post();
                echo wp_get_attachment_image( get_the_ID() );
            }
        }
    }
    
  2. I have added rand and posts_per_page to the last answer

    $query = new WP_Query( array( 'post_type' => 'custom-post', 'posts_per_page' => 30, 'orderby'=>'rand' ) );
    if( $query->have_posts() ){
        while($query->have_posts()){
            $query->the_post();
            $image_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'posts_per_page' => 1, 'post_parent' => get_the_ID() ) );
            while( $image_query->have_posts() ) {
                $image_query->the_post();
                echo wp_get_attachment_image( get_the_ID() );
            }
        }
    }