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.


Posted

in

by

Comments

7 responses to “Get WordPress Featured Image URL”

  1. juan avatar

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

  2. Jesse avatar

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

  3. Aldo avatar

    Thanks for the code buddy 😀

  4. CK13 avatar
    CK13

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

  5. Ionut Irimia avatar

    You saved my life. Thank you! 🙂

  6. Jauhari avatar

    Where is the Code?

    1. Mark Wilkinson avatar

      Should be there now!

Leave a Reply

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