Get recent posts with thumbnail

I want to ger several recent posts. So I use wp_get_recent_posts. But I get only first image.

<?php $args = array( 'numberposts' => '3' );

$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
    echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> ';
        if ( has_post_thumbnail() ) { 
        the_post_thumbnail('thumbnail');
    }
}
?>

2 Answers
2

Actually, the condition is always returning false because you are not passing the post id to the function has_post_thumbnail() and the function always getting the default value which is null.

has_post_thumbnail( $recent["ID"] ).

Same with the function get_the_post_thumbnail().

get_the_post_thumbnail( $recent["ID"] ).


$args = array( 'numberposts' => '3' );

$recent_posts = wp_get_recent_posts($args);

foreach( $recent_posts as $recent ){
   if ( has_post_thumbnail( $recent["ID"]) ) {
      echo  get_the_post_thumbnail($recent["ID"],'thumbnail');
    }
}

But if you use the functions has_post_thumbnail(); and get_the_post_thumbnail() inside the WordPress The_Loop then you don’t need to pass the post id.


$args = array( 'posts_per_page' => '3' );
$recent_posts = new WP_Query($args);
while( $recent_posts->have_posts() ) { 

   $recent_posts->the_post() ; 

   if ( has_post_thumbnail() ) {
      echo  get_the_post_thumbnail();
    }
}

wp_reset_postdata();

Leave a Comment