Get WordPress Featured Image URL

I have recently been working on a client site that used the excellent WordPress Post Thumbnail feature (or Featured Image as it is now referred to in the WordPress dashboard). I came across a small problem in that when using the function the_post_thumbnail() to display the featured image of a post, it also returns the tag as well as the URL of the image. Therefore I set about finding a way to solve this problem.

I have recently been working on a client site that used the excellent WordPress Post Thumbnail feature (or Featured Image as it is now referred to in the WordPress dashboard). I came across a small problem in that when using the function the_post_thumbnail() to display the featured image of a post, it also returns the <img> tag as well as the URL of the image. Therefore I set about finding a way to solve this problem.

Having looked on the Internet for some answers I came across Lee Willis’ post on the same thing which outlines an excellent solution to the problem. One of the commenters asked where to put the code, and although I knew t his I thought it would be a good idea to package this up into a little PHP function that you could then call in your template files.

Place the following into your themes functions.php file:

https://gist.github.com/4106040

To display the featured image URL you can echo mdw_featured_img_url( 'medium'); in your template file. You can replace ‘medium’ above for the size of the featured image URL that you want to return e.g. thumbnail, large or full. Even custom sizes work here that you had added using the add_image_size() function. Of course if you echo the function above it will display the URL on your page but you will probably want to use it in PHP one way or another.

7 Comments

juan May 17, 2012 Reply

This won’t work if you have a gallery of images attached to the post. Any ideas how to fix it?

Jesse June 12, 2012 Reply

seriously… you are the man!!! Thank you!!!

Aldo November 7, 2012 Reply

Thanks for the code buddy 😀

CK13 July 1, 2013 Reply

Thank you very much. Was searching for this all day.

Ionut Irimia July 2, 2013 Reply

You saved my life. Thank you! 🙂

Jauhari April 30, 2014 Reply

Where is the Code?

Mark Wilkinson May 1, 2014 Reply

Should be there now!

Leave a Reply