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.

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:

if(has_post_thumbnail()){
    the_post_thumbnail();
}
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);
    }
} 
share|improve this question
    
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..."? –  MikeSchinkel Feb 9 '11 at 19:56
    
Yes! Thanks for catching that...I will edit the post. –  notlaura Feb 9 '11 at 21:46
add comment

2 Answers

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.

share|improve this answer
add comment
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;
    }
}
share|improve this answer
    
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? –  notlaura Feb 10 '11 at 3:04
    
@notlaura How is your loop structured when you are in a category? –  Cronco Feb 16 '11 at 12:34
add comment

Your Answer

 
discard

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.