【问题标题】:Wordpress Featured Image as a backgroundWordPress 特色图片作为背景
【发布时间】:2013-11-26 23:49:45
【问题描述】:

我正在尝试将帖子的特色图片作为背景图片回显。我见过几个地方这应该是可能的,但我似乎无法让它为我自己工作。

//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 . '"/>'; ?>

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

【问题讨论】:

  • 您似乎试图将图像作为 div 的背景?将其用于页面背景...body{ background-image:url('&lt;?php echo $image; ?&gt;');}
  • 是的,我正在尝试制作 div 的特色图片而不是 body

标签: php wordpress


【解决方案1】:

检查此代码,让我知道它是否适合您 --

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

【讨论】:

  • 非常感谢!完美运行
【解决方案2】:

如果你想使用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

【讨论】:

  • 这仍在拉取完整尺寸的图像。不过,我很感谢您的回复。
  • @Travis,你没有提到尺寸,我想只是想要原始尺寸,无论如何,你得到了答案。
猜你喜欢
  • 2015-09-28
  • 2018-04-03
  • 1970-01-01
  • 2015-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多