-5

As you know the result of the the_post_thumbnail() is an image tag. I need this image tag to store at a kind of collection or Array. I'm using the following code but it doesn't help me out. And I want to use it at another place and print out as an image tag.

<?php $tmp_query = new WP_Query('showposts=6');
$counter=0;
while ( $tmp_query->have_posts() ) : $tmp_query->the_post();

 $arr[$counter]=the_post_thumbnail();
 $counter++;
 <?php endwhile;wp_reset_query(); ?> 
4

4 Answers 4

3

With a tiny bit of research, I'm pretty sure you could have created this yourself:

$featimage = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' )[0];
$printable_url = '<img src="' . $featimage . '">';

echo $printable_url;

Edit: Since PHP 5 is defunct, you can reference the first node in the array ([0]) directly. No need for intermediate storage of the full array.

1

Most WordPress functions that echo a result have sister function that return the result. To find them, go to the the Codex reference page for the function you are using. For this function, search Google with this phrase:

site:codex.wordpress.org the_post_thumbnail

Click on the link to the function then on the Related section and you will find other functions related to this one, including a link to the get_the_post_thumbnail() function.

The WordPress community has added most WordPress functions to the Function Reference and to the Template Tags sections of the Codex.

0

I too was rather confused by a similar attempt to use the_post_thumbnail() and it's alternate get_the_post_thumbnail(). Patrik's previous answer worked very well for me on that occasion, and I have since had good success with a combination of the two.

I had no luck with:

get_the_post_thumbnail('thumbnail');

but rather better success including $post->ID

get_the_post_thumbnail($page->ID, 'thumbnail');

The saddest part is that it is all in the WP codex... I just appear to have forgotten 'how' to read :)

0

First you get the ID of the attachment (featured image of the post) of your post with get_post_thumbnail_id(get_the_ID()) and then you pass that ID as an argument to the wp_get_attachment_image_src() function which returns the URL of that attachment.

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'full' )[0];

After that you can simply echo the variable and voila, you got the image.

echo '<img src="'.$image_url.'" />
1
  • You have added the same answer as I did, except ~4 years later. Apr 7, 2021 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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