WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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
A bit more description around that snippet would be helpful. – David Oct 3 '15 at 10:58

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.