Enable last 3 posts on template page with thumbnails

Hi im trying to add the_post_thumbnail to an echo statement of the code below but Im getting errors,

<?php
 $args = array( 'numberposts' => '3' );
 $recent_posts = wp_get_recent_posts( $args );
 foreach( $recent_posts as $recent ) {
 echo '<div> <a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </div> '; } ?>

How exactly are you adding the_post_thumbnail and what’s the error?

the_post_thumbnail() needs to be used within a loop. To use it with that setup you’d need to query it using get_the_post_thumbnail($recent['ID'])

1 Like

Okay found a better solution which hopefully others can use.

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

 <?php foreach($recent_posts as $post) : ?>
                    <div>
                       <a href="<?php echo get_permalink($post['ID']) ?>">
  <?php echoget_the_post_thumbnail($post['ID'], 'thumbnail'); ?>
  <!--<p><?php echo $post['post_title'] ?></p>--> 
  </a> 
  </div>
  <?php endforeach; ?>

Remember to enable Post Thumbnails, your theme must include add_theme_support( 'post-thumbnails' ); in its functions.php file.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.