How to retrieve the WordPress Featured Image URL

Home/Wordpress tricks/How to retrieve the WordPress Featured Image URL

How to retrieve the WordPress Featured Image URL

Sometimes you need the source url or path to a featured image. The reason might be that you want to use it as background somewhere or use it in src of img tag. There can be several reasons why you need the url to featured image of a post or page. Here is a trick which can be used to retrieve the url and then use it as background for a div

<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $featured_image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div style='background-image: url("<?php echo $featured_image_url [0]; ?>
<?php endif; ?>

Remember to do $featured_image_url

[0] because $featured_image_url is an array and we want to access the first member of it.Isn’t this a great trick?

Yumna Tatheer

Yamna Tatheer is a WordPress Plugin developer and a Top-Rated Upwork professional. She is a part-time blogger from Lahore and loves to write about wordpress and freelance industry.

More Posts

Follow Me:
Facebook

About the Author:

Yamna Tatheer is a Wordpress Plugin developer and a Top-Rated Upwork professional. She is a part-time blogger from Lahore and loves to write about wordpress and freelance industry.

2 Comments

  1. Ricardo May 28, 2012 at 5:38 pm - Reply

    Hey! Thanks I’ve been looking for this. It works! Check this out http://tiswc.com/category/for-bride-and-grooms/

    Although I’m still trying to figure out how to put the featured image not as background but as actual image replacing the boring laptops.

    I have the this <img class="pic-cinema" src="/images/pic-double.png” />

    (note: the laptop pic filename is pic-double.png)

    Can you help?

    • Emerald May 29, 2012 at 5:14 am - Reply

      you can use the above in img tag easily by doing

      <img class="pic-cinema" src="<?php echo $featured_image_url[0]; ?>" />
      

      Hope this helps.

Leave A Comment