I’m making a widget that shows a set of images from recent custom posts. I want to run the following query:
SELECT p.*
FROM wp_posts p
WHERE post_type="attachment"
AND post_mime_type LIKE 'image%'
AND post_parent IN (
SELECT ID
FROM wp_posts
WHERE post_type="my_custom_post_type"
)
ORDER BY post_date DESC
LIMIT 10;
and receive an array of attachment objects. I am unclear on the canonical WordPress method for doing something like this. Where should I start?
4 s
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;
}