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 want to show thumbnails next to my posts in archive page, however it only shows thumbnails if the posts has a featured image.

So I want to show thumbnail for the image attached to the post, but I don't know how to.

At the moment I am using the following code to show thumbnails if set as featured.

<?php if ( has_post_thumbnail()) : ?>
   <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
   <?php the_post_thumbnail(thumbnail, array('class' => 'alignleft')); ?>
   </a>
<?php endif; ?>

Any suggestions are appreciated

share|improve this question
    
possible duplicate: wordpress.stackexchange.com/q/57476/10691 — actually a search on WPSE should help you out. :) –  its_me Jul 14 '12 at 17:45
add comment

1 Answer 1

You can check if the post as a thumbnail and if not the get the first image in the post ex:

<?php
$size = 'thumbnail';
if ( has_post_thumbnail() ) {
    ?>
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
        <?php the_post_thumbnail($size, array('class' => 'alignleft')); ?>

   <?php
} else {
    $attachments = get_children( array(
        'post_parent' => get_the_ID(),
        'post_status' => 'inherit',
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'order' => 'ASC',
        'orderby' => 'menu_order ID',
        'numberposts' => 1)
    );
    foreach ( $attachments as $thumb_id => $attachment ){ //this was missing
        ?>
        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
        <?php echo wp_get_attachment_image($thumb_id, $size); ?>
        </a>
        ?>
    }
}
?>
share|improve this answer
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.