Image URL with the_post_thumbnail()

Asked

Viewed 1,529 times

3

How can I extract only the URL (attribute value src) of an image generated by the function the_post_thumbnail and assign it to an image?

The result I’m looking for would be something like:

<img src="<?php the_post_thumbnail(); ?>">

2 answers

3


If you’re inside the Loop, the post ID is known by WP, so just use the function get_post_thumbnail_id() parameter-less.
If you’re outside the Loop, is a matter of using get_post_thumbnail_id($post_id).

And with that information at hand, use the function wp_get_attachment_image_src indicating the Leandro.

Example:

$img = wp_get_attachment_image_src( get_post_thumbnail_id() );
echo "<img src='$img[0]' />";

How it works: the function the_post_thumbnail is a simple encapsulation for function get_the_post_thumbnail, which in turn ends by calling the function wp_get_attachment_image.

1

You can do it this way:

<?php
  $imagem = wp_get_attachment_image_src( $attachment_id, $size, $icon );
?>
<img src="<?php echo $imagem[0]; ?>" />

Here is the documentation if you have any questions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.