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 <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 responses

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

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

  3. Thanks for the code buddy 😀

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

  5. You saved my life. Thank you! 🙂

  6. Where is the Code?

    1. Should be there now!

Leave a Reply

Your email address will not be published. Required fields are marked *