WordPress auto generated thumbnails issue

I have the following code to pull the auto generated thumbnail images from a post which I use to display in the archive page. The code works fine on my local server but as soon as I uploaded it to the web, it doesn’t work.

—-EDIT—–

Read More

What it now displays is the same thumbnail for every post, the one linked to the first post entered. Any ideas why this might be?

    <ul>

 <?php query_posts('cat='.get_query_var('cat').'&order=ASC'); ?>

    <?php if (have_posts()) : ?>

        <?php while (have_posts()) : the_post(); ?>

        <?php
//Get images attached to the post

$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'numberposts' => -1,
        'order' => 'DESC',
    'post_status' => null,
    'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        $img = wp_get_attachment_thumb_url( $attachment->ID );
                break;
        }
}
?>

            <li>
                <img src="<?php echo $img; ?>" alt="" />
                <h2 class="small"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
            </li>                

        <?php endwhile; ?>

      <?php endif;?>

      </ul>

Related posts

Leave a Reply

2 comments

  1. In response to your edit. You’ll want to make sure you reset $img after each iteration of the while() loop. Then you’ll want to do a check to make sure its set before writing the image tag. This will stop the same thumbnail from repeating. Sample code is below.

    Right now it’s repeating because it’s finding an image for the first post but not for the others. But $img is set on the first post so it continues using it for all the others because it never gets reset or changed.

        <ul>
    
     <?php query_posts('cat='.get_query_var('cat').'&order=ASC'); ?>
    
        <?php if (have_posts()) : ?>
    
            <?php while (have_posts()) : the_post(); ?>
    
            <?php
    //Get images attached to the post
    $img = false;
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => -1,
            'order' => 'DESC',
        'post_status' => null,
        'post_parent' => $post->ID
    );
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            $img = wp_get_attachment_thumb_url( $attachment->ID );
                    break;
            }
    }
    ?>
    
                <li>
                    <?php if ($img): ?><img src="<?php echo $img; ?>" alt="" /><?php endif; ?>
                    <h2 class="small"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
                </li>                
    
            <?php endwhile; ?>
    
          <?php endif;?>
    
          </ul>