0

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.

1

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
}

0
if ( gallery_shortcode( $post->ID ) ) echo do_shortcode( '[gallery]' );
  • 1
    A bit more description around that snippet would be helpful. – David Oct 3 '15 at 10:58

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.