kaydee
kaydee

Reputation: 23

Set Featured Image as Background Image in WordPress

I've been trying to set the featured image as the background image on my blog. It's a single columned custom WordPress theme I am developing.

My idea is something like medium.com and blog.pickcrew.com

Can you guys please help me in getting it?

Thanks much!

Upvotes: 2

Views: 2111

Answers (2)

birgire
birgire

Reputation: 11378

You can try the following code snippet.

Save it to the file /wp-content/plugins/featured-image-background/featured-image-background.php and activate it:

<?php
/**
 * Plugin Name:        Featured Image Background 
 * Description:        Featured image as background for single posts
 * Plugin URI:         http://stackoverflow.com/q/23388561/2078474   
 */

function so_23388561_wp_head()
{
    if ( is_single() )
    {
        if ( has_post_thumbnail( get_the_ID() ) )
        {
            $image = array_shift( 
                        wp_get_attachment_image_src( 
                            get_post_thumbnail_id( get_the_ID() ),
                            'full' 
                        ) 
                    );
            printf( '<style>
                        body { 
                            background-image: url("%s") !important;
                            background-size: cover;
                        }
                     </style>', 
                     $image 
            );
        }
    }
}

add_action( 'wp_head', 'so_23388561_wp_head' );

You might want to use another CSS selector than body, perhaps div#background?

In general I use get_queried_object_id() to get the post ID outside the loop, but get_the_ID() should work in this case.

We're using the wp_head hook, so make sure your theme has the wp_head() function.

Hopefully you can modify it to your needs.

Upvotes: 3

Maidul
Maidul

Reputation: 418

You can try the following code

  <?php  $body_background = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'full' ); ?>
    <body style="background-image: url(<?php echo $body_background['0'];?>)">
    ....
    </body>

Upvotes: 1

Related Questions