How to determine if a post has attached images?

I would like to know how I can determine if a post/page has an image gallery (not documents/videos etc)?
I am not talking about gallery shortcode as shown here Check if post/page has gallery?

so that

if (has_gallery = true){

  //Do Something
}

else {
  // Do Something else
}

2 Answers
2

You could use get_posts and search for image attachments.

<?php
$images = get_posts(array(
    'post_parent'    => $the_parent_to_check, // whatever this is
    'post_type'      => 'attachment', // attachments
    'post_mime_type' => 'image', // only image attachments
    'post_status'    => 'inherit', // attachments have this status
));

if($images)
{
     // has images
}
else
{
     // no images. :(
}

Might be more efficient to write a custom SQL query to check for the count. Depends on whether you want to do something with the attachment posts or not.

Leave a Comment