how to test for attached image

I am trying to find out whether or not a post has images. If it does, I then want to know if a featured image was specified for the thumbnail – if not, the get_thumb() function will assign an image from the gallery of that post. However, if a post doesn’t have images, I want to use a span class to occupy the thumbnail space.

Here’s the statement I wrote:

Read More
if(has_post_thumbnail()){
    the_post_thumbnail();
}
elseif(is_attachment()) {
    echo get_thumb($post->ID); 
}
else {
    <span class="no_thumb"></span>
} 

It adds a 150×150 span to all posts without featured images. However, where images from get_thumb() should be, the span shows up instead. Essentially, it’s either the span or the featured image and the $get_thumb never appears.

For reference, here’s the get_thumb() function:

function get_thumb ($post_ID){
    $thumbargs = array(
    'post_type' => 'attachment',
    'numberposts' => 1,
    'post_status' => null,
    'post_parent' => $post_ID
    );
    $thumb = get_posts($thumbargs);
    if ($thumb) {
        return wp_get_attachment_image($thumb[0]->ID);
    }
} 

Related posts

Leave a Reply

2 comments

  1. function has_image_attachment($post_id) {
        $args = array(
            'post_type' => 'attachment',
            'post_mime_type' => 'image/jpeg',
            'numberposts' => -1,
            'post_status' => null,
            'post_parent' => $post_id
        ); 
    
        $attachments = get_posts($args);
    
        if(is_array($attachments) && count($attachments) > 0) {
           //Has image attachments
           return true;
        } else {
           return false;
        }
    }
    
  2. is_attachment() doesn’t work like that – it is conditional tag to detect attachment page, not availability of attachments.

    I don’t remember any ready-made function to fetch/check for all attachments. Just use your get_post() call from get_thumb() – if it fetches nothing then there are no attachments.