Wordpress特色图片作为背景



我正在尝试将帖子的特色图像作为背景图像进行回声处理。我已经看到了一些地方,这应该是可能的,但我似乎无法让它为我自己工作。

//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>

但如果我使用这个,我可以回声出缩略图

<?php echo '<img src="' . $image . '"/>'; ?>

我觉得我错过了一些小而愚蠢的东西,但那是什么?

检查这段代码,让我知道这是否适用于你——

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

如果您想使用post thumbnail作为背景图像,则不能使用此函数,因为它会打印带有缩略图的img元素,而可以使用wp_get_attachment_url

$url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );

然后像一样使用此图像作为背景

<div style="background:url('<?php echo $url; ?>');"></div>

这是在循环内部,如果你想在循环外部使用它,那么你必须传递post ID

最新更新