Dileet
Dileet

Reputation: 2064

Wordpress featured image as div background image

How can I set the featured images on all my posts to be outputted as a background image to a div. For example

<div class="postimg" style="background-image:url('https://s3.amazonaws.com/ooomf-com-files/8jLdwLg6TLKIQfJcZgDb_Freedom_5.jpg')"></div>

Currently the featured image is being outputted as a regular image using this helper <?php the_post_thumbnail( 'wpbs-featured' ); ?>

Upvotes: 1

Views: 4579

Answers (3)

Shebin Xavier
Shebin Xavier

Reputation: 63

Use this

<div style="background-image:url('<?php echo wp_get_attachment_url( get_post_thumbnail_id() );?>')"></div>

Upvotes: 2

Shashank Singh
Shashank Singh

Reputation: 1300

Try this...

<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">

</div>
<?php endif; ?>

Upvotes: 0

ggdx
ggdx

Reputation: 3064

I would suggest simply something along the lines of this Get post featured image URL and echo it out accordingly:

<?php
$img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "full");
$img = $img[0];
?>
<div class="postimg" style="<?php if($img){echo 'background:url('.$img.');';} ?>">

</div>

Upvotes: 2

Related Questions