5

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.

15

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 

}
  • Does it understand it without slash and image format identifier? – jayarjo Oct 10 '12 at 8:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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