Blog: WordPress
Male web developer coding

Get the URL of a Featured Image in WordPress

Avatar for John Locke

John Locke is a SEO consultant from Sacramento, CA. He helps manufacturing businesses rank higher through his web agency, Lockedown Design & SEO.

Sometimes it is useful to get the URL of a Featured Image in WordPress, instead of just outputting the image itself as HTML.

When would you use this?

If you need to get the URL in order to use it for a background image, as in a header at the top of the page, for example.

Here’s what that would look like.



<!-- PHP code for your WordPress template -->
<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
<div class="banner-image" 
    <?php if( $feat_image ) : ?>
        style="background-image: url(<?php echo $feat_image; ?>);"
    <?php endif; ?>
></div>

/* CSS for the finished HTML 
------------------------------ */

.banner-image {
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: cover;
  width: 100%;
}

/* Add the height and padding to this div that you need */

What is happening in the PHP code?

We are using the built-in function get_post_thumbnail_id to look up the ID of the Featured Image attached to this post.

We pass this as a parameter to another function, wp_get_attachment_url, which returns the URI for a given attachment. This function takes as a parameter the ID of the post you want to get the attachment URI from. This is why we are passing the other function as a parameter, because it gets the ID of the Featured Image of the post.

This value is then stored in a variable named $feat_image.

In the next line, we have our div for our full-width header section. We test to see if $feat_image contains a value. If it contains a value, (the URL of the Featured Image), then we add some inline styles to make that Featured Image the background-image of our .banner-image div.

If the $feat_image variable contains no value, no inline styles are output.

We then use the CSS to center the image in our div, and cover the full width and height of the div.

You would have to set a height for this diveither explicitly, or by using padding, to give it height.

This is only one way you can use the first two lines of the WordPress template shown above. The principle remains the same for getting the URL of the Featured Image of that particular post.

Avatar for John Locke

John Locke is a SEO consultant from Sacramento, CA. He helps manufacturing businesses rank higher through his web agency, Lockedown Design & SEO.

Join the Conversation

Your email address will be kept private. Required fields marked *.