简体   繁体   中英

Wordpress Featured Image as a background

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?

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; ?>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM