Reputation: 2245
I am trying to echo out the featured image of a post as a background image. I have seen a few places this should be possible but i cant seem to make it work for my self.
//Here i get the image as a thumbnail
<?php
if ( has_post_thumbnail()) {
$image = the_post_thumbnail('thumbnail');
}
?>
// Here i try to get it as a background image and nothing
<div style="width:405px;height:277px;background-image:url('<?php echo $image; ?>');">
<img src="<?php bloginfo('template_url'); ?>/images/foreground.png"/>
</div>
But if i use this i can echo out the thumbnail
<?php echo '<img src="' . $image . '"/>'; ?>
I feel like i am missing something small and stupid but what is it?
Upvotes: 0
Views: 1423
Reputation: 9782
Check this code and let me know if that works for you --
<?php if ( has_post_thumbnail() ): ?>
<?php
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail');
?>
<div style="width:405px;height:277px;background-image:url('<?php echo $image[0]; ?>');">
<img src="<?php bloginfo('template_url'); ?>/images/foreground.png"/>
</div>
<?php endif; ?>
Upvotes: 1
Reputation: 146191
If you want to use post thumbnail
as a background image then you can't use this function, because it prints an img
element with the thumbnail image, instead you can use wp_get_attachment_url
$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
Then use this image as a background like
<div style="background:url('<?php echo $url; ?>');"></div>
This is inside the loop and if you want to use it outside of the loop then you have to pass the post ID
.
Upvotes: 0