Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

As far as I know, there's not a simple function that will return true if a post has an attachment. With that in mind, what's the best way to determine if a post has an attachment (or even better, has an image attachment)? I'm automatically inserting a shortcode on posts, but would like that to only happen if there is actually an image attached to the post.

share|improve this question
add comment

1 Answer

up vote 10 down vote accepted

I think this should work:

$attachments = get_children( array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image') );

if ( $attachments ) {

 // do conditional stuff here 

}
share|improve this answer
    
That works perfectly, thanks. –  tnorthcutt Mar 10 '11 at 18:16
    
Does it understand it without slash and image format identifier? –  jayarjo Oct 10 '12 at 8:40
    
Perfect! Thanks! –  trusktr Jul 14 '13 at 20:15
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.