How To Get Post Thumbnail As Background Image In WordPress

Quick Summary
- Pass get_post_thumbnail_id() to wp_get_attachment_url() inside the Loop, then print the URL in an inline background-image style.
- The attachment URL points to the full-size original, while get_the_post_thumbnail_url() with a size such as large returns a smaller version.
- Escape the URL with esc_url(), check has_post_thumbnail() for posts without an image, and give the element display: block and dimensions.
Many designs place the featured image behind text, for example in a hero banner or a card. For that you need the image’s URL rather than the <img> tag that the_post_thumbnail() prints. These two steps work in any WordPress theme template.
Step 1: get the featured image URL
Use this inside the Loop, or anywhere the global $post is set, for example in single.php or a template part.
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );get_post_thumbnail_id()returns the attachment ID of the post’s featured image.wp_get_attachment_url()turns that ID into the URL of the original uploaded file, at full size.- If you’d rather load a smaller version,
get_the_post_thumbnail_url( $post->ID, 'large' )returns the URL of a specific image size in one call.
Step 2: use it as an inline background
Print the URL inside a style attribute on the element that should show the image. Fill in the empty href and class with your own link and class.
<a href="" class="" style="background-image: url(<?php echo $url; ?>);" ></a>- Escape the URL when you print it:
echo esc_url( $url );is safer than a plainecho $url;. What esc_url, esc_attr and esc_html are for explains why. - If a post has no featured image, no URL is printed and the background stays empty. Wrap the markup in
if ( has_post_thumbnail() )or provide a fallback image. - An empty link has no size of its own, so the image won’t show until you give the element
display: block, a width and a height in your CSS.background-size: covermakes the image fill the box.
Related articles
- the blog page’s featured image as a banner background: the same technique on the Posts page, where the usual call finds no thumbnail
- picking an image size for an ACF image field: the size-aware approach for Advanced Custom Fields images

