Sign up ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
share|improve this question
Do you mean: "if a post has images attached to it"? .... If so, please edit the Question to make this clear. –  brasofilo Dec 4 '12 at 17:04
I meant gallery attached to it... people can attach images to via WYSIWYG to the actual post... but I want to actually determine if post has a gallery...? –  MonteCristo Dec 4 '12 at 17:33
In WordPress parlance "gallery" = "images attached to a post". –  Chip Bennett Dec 4 '12 at 19:06

2 Answers 2

You could use get_posts and search for image attachments.

$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

     // has images
     // 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.

share|improve this answer

To test if a post has a gallery write a small helper function:

function has_gallery( $post = NULL )
    if ( ! is_null( $post ) )
        $post = get_post( $post );

    if ( ! $post )
        if ( ! isset ( $GLOBALS['post'] ) )
            return FALSE;

        $post = $GLOBALS['post'];

    return FALSE !== strpos( $post->post_content, '[gallery' );


if ( has_gallery() ) 
    // do something

Note that a post with a gallery doesn’t necessary has attachments: You can create a gallery with images that are attached to other posts.

share|improve this answer
From the question "I am not talking about gallery shortcode" –  chrisguitarguy Dec 4 '12 at 19:18
Hm, then I misread I meant gallery attached to it … contradictory description. –  toscho Dec 4 '12 at 19:21

Your Answer


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.