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?
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):
What I recommend is one instance of
WP_Query
for looping through all the custom post type post and thenget_posts()
to retrieve the attachments for each post. Here’s an untested code snippet that should do what you want:Hope this helps.
Maybe something like this:
If all you’re interested in is the number of attachments for a particular post type, you can modify Chris’ function slightly to the following: