Feature img as a bg for single WordPress entries

November 21, 2014

The following snippet when placed within a WordPress post loop will display a feature image uploaded via your media uploader and place it as a background image within a div tag.

Custom CSS will be required to display the image.


<?php if ( has_post_thumbnail( $post->ID ) ) : ?>
  <?php
    $image = wp_get_attachment_image_src(
              get_post_thumbnail_id( $post->ID ),
              'single-post-thumbnail'
            );
$image = $image[0];

?>

<div class=“feat-img—bg” style=“background-image: url(’<?php echo $image; ?>’)”></div> <?php endif; ?>

More information about post thumbnails can be found on the WordPress Codex.