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

I am a Computer Science graduate and a part time blogger from Lahore, Pakistan. I am a PHP programmer and a wordpress expert.

More Posts

Follow Me:
Facebook