3

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');
    }
}
?>
6

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();
| improve this answer | |
2

In order to use the_post_thumbnail, you need to initialize a loop. So more like this:

<?php 
$args = array( 'posts_per_page' => '3' );
$recent_posts = new WP_Query($args);
while( $recent_posts->have_posts() ) :  
    $recent_posts->the_post() ?>
    <li>
        <a href="<?php echo get_permalink() ?>"><?php the_title() ?></a> 
        <?php if ( has_post_thumbnail() ) : ?>
            <?php the_post_thumbnail('thumbnail') ?>
        <?php endif ?>    
    </li>
<?php endwhile; ?>
<?php wp_reset_postdata(); # reset post data so that other queries/loops work ?> 

(I put the thumbnail inside the <li> tags because anything besides <li> inside a <ol> or <ul> is invalid html.)

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.