get attachments for all posts of particular post type

It seems like a bit of a waste to run through two loops just to use some built in API functions that weren’t designed for a use case like this.

I think you’re better off to use your SQL combined with the wpdb class — faster and cleaner.

Example (with modified SQL):

<?php
function wpse52315_get_attach()
{
    global $wpdb;
    $res = $wpdb->get_results("select p1.*
        FROM {$wpdb->posts} p1, {$wpdb->posts} p2
        WHERE p1.post_parent = p2.ID 
           AND p1.post_mime_type LIKE 'image%'
           AND p2.post_type="your_cpt"
        ORDER BY p2.post_date
        LIMIT 10;"
    );
    return $res;
}

Leave a Comment