[wp-hackers] Query to return only posts that have an image attachment

Adam Holzband adamholz at gmail.com
Thu Jan 21 06:41:01 UTC 2010

The code is not very complex but I can give you an example with some

Let's say there are 20 posts in a category, 10 of which have images.  Of the
most recent 10 posts however, only 4 have images.

So on a category template you would have the psuedo-code loop below, which
would only show 4 posts.  Instead, I would like to show the 10 posts with
images (or whatever # is in posts_per_page/settings):

while (have_posts()) : the_post();
 $args = array('post_type' => 'attachment', 'post_mime_type' =>
'image',  'numberposts'
=> 1, 'post_status' => null, 'post_parent' => $post->ID);
$images = get_children($args);
if ($images) {
***** DISPLAY POST *****

I've thought up some kludges that seem ok, but am assuming that I will need
to replace or adjust the query to do this efficiently.  I am wondering if
there is a better option and/or what the best query would be.  Thanks for
the help.


More information about the wp-hackers mailing list