Use post thumbnail as div background

I’m having trouble implementing a way of using the set WordPress post thumbnail as a background for a div which will include the whole post.

Basically, I need a way to call for the thumbnail URL in the index.php file. Something like this

Read More
<div style="background: url(<?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'normal-bg' ); } ?>) ">

Now what should happen is that the above would find a thumbnail for the post and use it as the background image. The thumbnail class would be “normal-bg”, since there are thumbnail classes in my functions.php with different heights (since some posts can have more text etc.). However, I’ve been unable to make the above code work.

Sorry if the whole concept sounds confusing, it’s a bit too hard to explain 🙂

Related posts

Leave a Reply

1 comment

  1. <div<?php
    
        if ( $thumbnail_id = get_post_thumbnail_id() ) {
            if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, 'normal-bg' ) )
                printf( ' style="background-image: url(%s);"', $image_src[0] );     
        }
    
    ?>>
    

    Code should be pretty self explanatory – codex on wp_get_attachment_image_src.

    As for how I’ve formatted it; I find this the cleanest, easiest to read, without outputting unnecessary whitespace:

    <div style="background-image: url(http://example.com/wp-content/uploads/normal-bg.jpg);">