WordPress Featured Image URL
I love WordPress. I also love utilizing WP’s Featured Image or Thumbnail Image for developing themes and site. Sometimes, I want to take advantage of the fact that WordPress has already resized the images on the server, but I’d like to use the image URL for purposes such as using the image as a background image of an element… In such a case I’d like to have the WordPress featured image URL handed to me directly.
So, here’s a single line of code that I use to make it simple. It must be used within the loop or a query of some kind.
<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'medium' ); $url = $thumb['0']; ?>
Make sure to change ‘medium’ to include whichever size you’re looking for. The options are:
- array(100, 100)
Obviously the last option would be for you to specify a specific resolution with a width followed by a height (no quotes in this option).
Then I simply echo the url variable into the code like this:
<a style="background-image:url(<?php echo $url; ?>)" href="https://three17design.com" >317</a>
I find that I use this often. You can do a lot more with background images these days with the new CSS3 features such as cropping with background sizes and positions, and having WordPress hand me the most appropriate file is very useful.