Set Post Featured Image or Thumbnail as Background Image in WordPress


I will show you in different ways to set a post featured image or thumbnail as a background image in WordPress.

Method 1:  Generally, we use the_post_thumbnail() to display post featured/thumbnail image. To set a background image we need the image URL but the problem is the_post_thumbnail()return  <img> tag, not URL. So, we need to return the featured image URL. Let’s take a look at the code below

$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
echo '<div class="post-banner" style="background: url('. $url.')">';

Method 2: You can use get_the_post_thumbnail_url() instead of wp_get_attachment_url() Now the code will be :

<?php $url = get_the_post_thumbnail_url(); ?>
<div class"post-banner" style="background: url('<?php echo $url;?>')"></div>

Method 3: In this method first, we need to retrieve the featured image. We’ll use the wp_get_attachment_image_src() function to do this. This function requires image ID as a parameter, which we will get from  get_post_thumbnail_id() function. Now, include the id of the post as a parameter for get_post_thumbnail_id (which we retrieve using $post->id). The second parameter is the size of the image. The default is ‘thumbnail’, but we want the full size of the original image or custom size of the image. To get the original size of the image we have to use the keyword ‘full’. For a custom size, pass in an array, something like array (800, 300), which would be width 800 px and height 300 px.

<?php $bgImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>

The wp_get_attachment_image_src() function returns an array that includes the URL of the image, the width in pixels, the height in pixels, and a boolean, true if the image has been re-sized, or false if the image is original size. We’ll use a variable named $bgImg to hold the returned results.

All we really need the URL of the image. It’s the first item in the array, so we’ll reference it like so $bgImg[0]

And here is the full code of set post featured image or thumbnail as a background image

<?php $bgImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' ); ?>
<div class"post-banner" style="background: url('<?php echo $bgImg[0];?>')"></div>

Leave a Reply

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like