Post Pic

WordPress tip: Get thumbnail url

Today, here’s a snippet that gives you the ability to extract the source of the post thumbnail image. It is super useful if you need the post thumbnail url to use in your code.

Simply paste the following code on your theme file, within the loop.

<?php
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id);
$image_url = $image_url[0];
?>

Thanks to WP Snippets for the cool tip!

12 Responses

Mar 15 2012 22:34

You could simplify and make this a little more efficient in this way:

Less variable use and fewer lines.

Mar 15 2012 22:35

Gah. the previous comment stripped my code. May need to edit to make it show properly.

Mar 16 2012 06:40

Great, its simple short and sweet, earlier i used a lengthy code to achieve the same result

Mar 16 2012 11:10

How about wp_get_attachment_thumb_url()? :)

Mar 16 2012 16:14

Don’t forget about the width and the height the function you used returns, it’s always a good idea to include the attributes if you’re displaying your image on screen. Also, always check for has_post_thumbnail first:

if ( has_post_thumbnail() ) {
$image_id = get_post_thumbnail_id();
list( $src, $width, $height ) = wp_get_attachment_image_src($image_id);
echo “”;
}

If you’re paranoid you can esc_url and absint as well :)

Cheers!

~ K

Mar 16 2012 16:15

You should also get <pre> tags working :)

Apr 17 2012 14:55

Very nice!

I tried to understand wordpress theme better.
And I found this site.

very useful .
Thanks !!

May 07 2012 08:20

this site is very helpful to me…thanks guys…:)

Jun 13 2012 19:42

This snippet is very useful….thanks :)

Sep 25 2012 10:35

i tried the wp_get_attachment_thumb_url() but its not working, im using elegant themes.. pls help.. my account on ET already expired..

Nov 29 2012 06:18

Can you please simplify this for non techie wordpress newbies? I don’t even know what you mean by “the loop”? I just want to add an image to my side bar, was asked for the image URL and I can’t find it. Can you please, in simple terms, explain how to find the image URL for an image that you have downloaded onto your computer and want to insert into your website? Thanks.

May 02 2013 22:17

I usually use the way like Kontantin comment

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox