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.

How do I test whether there are any images attached to a post?

I'm using the gallery shortcode, but I want to put it in a conditional so the surrounding styling isn't displayed if the gallery is empty.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

You can check if an attachment for the given post exists with the get_posts function. This will create a new sql query - so there could be a performance issue.

// Util.class.php
class Util {
     public static function has_attachments() {
         $args = array(
            'post_type' => 'attachment', 
            'numberposts' => -1, 
            'post_status' => null, 
            'post_parent' => $post->ID

         $attachments = get_posts($args);

         if(!empty($attachments)) {
             return TRUE;
         } else {
             return FALSE;

// In template
require_once 'Util.class.php';
if (Util::has_attachments()) {
    // Display gallery

share|improve this answer
if ( gallery_shortcode( $post->ID ) ) echo do_shortcode( '[gallery]' );
share|improve this answer

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.