Question

I have a Wordpress-powered website with several custom post types, and I'm struggling to find a way to load the latest uploaded images from one of the custom post types only.

In other words, I know how to ask for the most recent 4 images added to the Wordpress media library, but I can't find a way to filter the attachments depending of the post type of their parent page (in this case, show only the images uploaded to 'Image Gallery' posts - not regular posts, not 'Video Gallery' posts, etc).

It feels like a very basic question, but for some reason I can't get this work and I'm really frustrated. Is there any way to get the post type of the post parent in the query? Or I should approach this issue from another angle?

Was it helpful?

Solution

I don't believe it's possible to use WP_Query to filter based on the post type of the parent. The most straightforward way around this is to use SQL and $wpdb->get_results() directly. This will also bypass all built in caching, etc so think about how your implementation will be used.

global $wpdb;

// the SQL statement to only fetch the N last attachments
$sql = <<<SQL
SELECT attachments.*
FROM {$wpdb->posts} attachments
-- join the parent post based on the parent_post value to filter by cpt
JOIN {$wpdb->posts} post
    ON post.ID = attachments.post_parent
    AND post.post_status = 'publish'
    -- pass in the custom post type
    AND post.post_type = %s
WHERE
    -- only fetch images, double percents for prepare()
    attachments.post_mime_type LIKE 'image%%'
ORDER BY attachments.post_date DESC
-- pass in the number to fetch
LIMIT %d
SQL;

$cpt = "your_custom_post_type";
$limit = 4;
$attachments = $wpdb->get_results( $wpdb->prepare( $sql, $cpt, $limit ) );
foreach ( $attachments as $attachment ){
    // $attachment will have all the rows from the posts table.
    $id = $attachment->ID;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top