Thumbnail is showing outside its div instead of inside it

The question:

I’m echoing the post thumbnail here:

echo '<div class="post-image right">' . the_post_thumbnail('featured-portrait-large') . '</div>';

And it works, but it’s outputting the image outside the div like this:

<div class="post-header-text">
  <img width="500" height="700" src="[IMAGE URL DELETED]" class="attachment-featured-portrait-large size-featured-portrait-large wp-post-image" alt="" loading="lazy">
  <div class="post-image right"></div>
</div>

What I want is:

<div class="post-header-text">
  <div class="post-image right">
    <img width="500" height="700" src="[IMAGE URL DELETED]" class="attachment-featured-portrait-large size-featured-portrait-large wp-post-image" alt="" loading="lazy">
  </div>
</div>

Could someone explain why and what I’ve done wrong?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

the_post_thumbnail() echo the output, hence that’s why the thumbnail is misplaced.

To manually echo the output, you should use get_the_post_thumbnail() instead:

echo '<div class="post-image right">' . // wrapped
    get_the_post_thumbnail(null, 'featured-portrait-large') . '</div>';

Or you can instead do this:

echo '<div class="post-image right">';
the_post_thumbnail('featured-portrait-large');
echo '</div>';

Method 2

You can simply get image url then add this url to image tag, I hope this will help you.

<?php 
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'medium', true);
$imageURL = $thumb_url[0];
?>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment