Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

Please help =)

share|improve this question

1 Answer 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() ){
        $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() ) {
            echo wp_get_attachment_image( get_the_ID() );
share|improve this answer
Good snippet, but I think it would be better if you use get_posts() –  Mamaduka Dec 6 '11 at 11:12
If you check the core files get_posts() itself instantiates a new WP_Query object. So that's why I prefer using WP_Query() directly. –  Joshua Abenazer Dec 6 '11 at 11:28
Thank you for your answer, but its not what i need: I want a loopable list of all the images which are attached to any posts of a certain type, regardless to which post they belong. I can see that your way does roughly the same, but it does not give a single query for all images. I used a custom SQL-query for this now. –  yoda2k Dec 6 '11 at 11:35
Query inside a loop, not a good idea! –  Ashfame Dec 6 '11 at 12:38

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.