Imagen destacada de Wordpress como fondo

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?

preguntado el 26 de noviembre de 13 a las 23:11

It looks like your trying to make the image the background of a div? Use this for the page background... body{ background-image:url('<?php echo $image; ?>');} -

Yeah i am trying to make the featured image of a div not the body -

2 Respuestas

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

respondido 27 nov., 13:04

Thank you very much! Works perfectly - Travis

Si quieres usar 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.

respondido 27 nov., 13:01

This is still pulling the full size image. I appreciate the response though. - Travis

@Travis, You didn't mentioned about the size and I thought just want to original size, anyways, You got the answer. - El alfa

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.