I am trying to make a shortcode that will take my latest 5 posts and render them on page. I get all the posts rendered correctly except for the image source, I receive it blank. Is it something I'm doing wrong?

$content = $content?$content:'Latest Posts';
$a = shortcode_atts(
$args = array('numberposts'=>$a['posts']);
$recent_posts = wp_get_recent_posts( $args, ARRAY_A );
echo '<div class="recent-posts">';
echo '<h1>'.$content.'</h1>';
foreach($recent_posts as $post){
    <div class="updated"><p><?php echo $post['post_title']; ?>. <a href="<?php echo get_permalink($post["ID"]); ?>"><img src="<?php the_post_thumbnail_url($post["ID"]); ?>"/>.</a></p></div>
 echo '</div>';
  • You must not use echo in a shortcode callback.
    – fuxia
    Commented Apr 8, 2016 at 22:23
  • Omg, I will never program during night, banged my head off the walls for 30 minutes but missed such a basic thing.
    – loliki
    Commented Apr 9, 2016 at 4:32

1 Answer 1


Image fix

You are using the incorrect function to return the image source url. Change

the_post_thumbnail_url( $post["ID"] )


get_the_post_thumbnail_url( $post["ID"] )

see https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/

To fix the echo

Use a $return variable like so:

$out = '<div class="recent-posts">';
$out .= '<h1>'.$content.'</h1>';
foreach($recent_posts as $post){
    $out .= '<div class="updated"><p>' . $post['post_title'] . '.<a href="' . get_permalink($post['ID']) . '">';
    $out .= '<img src="' . get_the_post_thumbnail_url( $post['ID'] ) . "'/>.</a></p></div>';
$out .= '</div>';

return $out;
  • Thanks man, I missed a basic thing, that I was looking for more than 30 minutes :D
    – loliki
    Commented Apr 9, 2016 at 4:34
  • @Radu033 if this was your solution, would you care to mark it as such? Commented Apr 9, 2016 at 10:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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