Liz Nix

Responsive Background Images Using the WordPress Featured Image

Recently, I wanted to create responsive background images using WordPress’s featured image feature.

One of the handy features of the WordPress media uploader is that it automatically creates multiple instances of your image at different dimensions. Thumbnail, medium, large and full images are available by default and it’s easy to add your own custom sizes.

The design for the site I was working on called for full width background images in the header. I wanted to use the smallest file size that would still look great depending on the device / viewport width, and still allow the client the ability to update the background image easily. I decided to use the featured image to allow the client to dynamically set the image on each page, and media queries to choose the WordPress generated image size for the current display width. Here’s the basic recipe.

First, in functions.php make sure your theme supports thumbnails, look for add_theme_support( 'post-thumbnails' );
and then declare any sizes you need in addition to the defaults using add_image_size(); inside your theme’s setup function. Parameters are the name and width (and optional height if you want your image to be cropped), for example:

	add_image_size( 'extra-large', 1000);
        add_image_size( 'xx-large', 1600);

You’ll need to use PHP to dynamically create the CSS, so if the featured image has been set add a <style> element to to your header.php like so:


<?php if (has_post_thumbnail($post->ID)){ ?>
<style>
body .site-header{
	background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'large'); ?>);
}
@media (min-width:768px){
	body .site-header{
		background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'extra-large'); ?>);
	}	
}
@media (min-width:1200px){
	body .site-header{
		background-image: url(<?php echo get_the_post_thumbnail_url($post->ID, 'xx-large'); ?>);
	}	
}
</style>
<?php } ?>

That’s all there is to it. For quick reference here are the default sizes if you’ve only enabled theme support for thumbnails:


the_post_thumbnail('thumbnail');       // Thumbnail (default 150px x 150px max)
the_post_thumbnail('medium');          // Medium resolution (default 300px x 300px max)
the_post_thumbnail('large');           // Large resolution (default 640px x 640px max)
the_post_thumbnail('full');            // Original image resolution (unmodified)