Shahar Galukman
Shahar Galukman

Reputation: 902

Displaying posts thumbnails in Wordpress show only first thumbnail

I want to display on the sidebar the latest posts title and thumbnail. So far I'm getting the posts title and only one thumbnail duplicated. You can see the result here.(only the first/oldest post image displaying)

Here is my code:

$rps = wp_get_recent_posts($params);
foreach($rps as $rp) :
    $args = array(
            'post_type' => 'attachment',
            'numberposts' => 1,
            'post_status' => null,
            'post_parent' => $post->ID
             );

    $attachment = current(get_posts( $args ));
?>
<a href="<?php echo get_permalink($rp['ID']);?>"><?php echo $rp['post_title'];?><?php echo wp_get_attachment_image( $attachment->ID, 'thumbnail' );?></a>
<?php endforeach; ?>

Thanks for any tips/assistance given.

Upvotes: 0

Views: 402

Answers (2)

Mangesh Parte
Mangesh Parte

Reputation: 2177

Replace 'post_parent' => $post->ID with 'post_parent' => $rp['ID'] . That's it. What you are doing is, you are passing current post's ID in $args for all posts.

Upvotes: 3

Moishy
Moishy

Reputation: 3648

run 2 queries

one outputs the first post. The second outputs everything else excluding the first

<?php $args = array( 'post_type' => 'attachment', 'posts_per_page' => 1, 'post_parent' => $post->ID);  
$first = new WP_Query( $args ); 
while ( $first->have_posts() ) : $first->the_post(); ?>
<a href="<?php echo get_permalink();?>"><?php the_title();?><?php echo wp_get_attachment_image( $first->ID, 'thumbnail' );?></a>
<?php endwhile; wp_reset_postdata(); ?>
<?php $args2 = array( 'post_type' => 'attachment', 'posts_per_page' => 1, 'post_parent' => $post->ID, 'offset' => 1);  
$rest = new WP_Query( $args2 );
while ( $rest->have_posts() ) : $rest->the_post(); ?>
<a href="<?php echo get_permalink();?>"><?php the_title();?><?php echo wp_get_attachment_image( $rest->ID, 'thumbnail' );?></a>
 <?php endwhile; wp_reset_postdata(); ?>

Upvotes: -1

Related Questions