Add WordPress Featured Image as Background Image

With WordPress, when you add a featured image to your page or post, the output of <?php the_post_thumbnail(); ?> shows up like this:

<img src="https://www.mikejohnsondesign.com/images/cool-image-here.jpg" />

If you try adding the post thumbnail code to a DIV:

<div style="background: url(<?php the_post_thumbnail(); ?>);">

the output will be:

<div style="background: url(<img src="https://www.mikejohnsondesign.com/images/cool-image-here.jpg" />);"></div>

The above does not work. So I was in need of finding a great way to strip out the
<img src="" /> code and just be left with the absolute path to the image. I found a simple tutorial here that explains how to do this. In short, here’s all the code you need:

<?php 
    global $post; 
    $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 5600,1000 ), false, '' ); 
?>
<div style="background: url(<?php echo $src[0]; ?> ) !important;">Your site content here...</div>

The end result will be:

<div style="background: url(https://www.mikejohnsondesign.com/images/cool-image-here.jpg);"></div>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.