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:

elseif(is_attachment()) {
    echo get_thumb($post->ID); 
else {
    <span class="no_thumb"></span>

It adds a 150x150 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);
  • You questions is confusing me. When you say "...where images from $get_thumb should be..." did you instead mean "...where images from get_thumb() should be..."? Feb 9, 2011 at 19:56
  • Yes! Thanks for catching that...I will edit the post.
    – laras126
    Feb 9, 2011 at 21:46

2 Answers 2

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;
  • Thanks! Still having problems though. I replaced is_attachment() with has_image_attachment() and added it to functions.php but now no posts (with or without thumbnails) are showing up when I view a category. Any ideas?
    – laras126
    Feb 10, 2011 at 3:04
  • @notlaura How is your loop structured when you are in a category?
    – Cronco
    Feb 16, 2011 at 12:34

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.