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

Dave Viner dave at vinertech.com
Thu Jan 21 20:55:19 UTC 2010

Just as a sidenote...

Not all images that appear in a post are attachments.  That is, an author
can upload an image into the Media Library, and then later insert that image
into a post.  The inserted image is not attached to the image.

So, depending on your need, selecting posts with attached images might be
more challenging than this attachment query.

Dave Viner

On Wed, Jan 20, 2010 at 10:41 PM, Adam Holzband <adamholz at gmail.com> wrote:

> The code is not very complex but I can give you an example with some
> psuedo-code.
> 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 *****
> }
> endwhile;
> 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.
> >
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers

More information about the wp-hackers mailing list