【问题标题】:Wordpress featured image with fallback as a background imageWordPress 特色图片,以后备图片作为背景图片
【发布时间】:2018-04-03 05:20:19
【问题描述】:

这是我第一次涉足 Wordpress,我正在尝试创建一个帖子页面。我已经提取了精选图片,但如果没有精选图片,我会尝试将其换成备用图片。

目前看起来像这样(循环内的 obvs):

<?php $thumb = get_the_post_thumbnail_url(); ?>

<div class="news-hero" style="background-image: url('<?php echo $thumb;?>')">
     <div class="page-title"><h1><?php the_title(); ?></h1></div>
</div>

这很棒,因为它会拉取我然后用 echo $thumb 位放置的网址。

我想我需要以某种方式将 $thumb 定义为缩略图 url 或另一个 URL,但不确定如何?

我已经设法将其作为列表页面的图像标记,但如果可以的话,我更希望能够将其作为背景图像(只是拉入 URL)。

这是列表目前使用的 - 但仅适用于 img 标签。

<div class="news-collation-img">
    <?php if ( has_post_thumbnail() ) {
          the_post_thumbnail();
          } else { ?>
          <img src="<?php bloginfo('template_directory'); ?>/img/news/fallback-image.jpg" alt="<?php the_title(); ?>" />
    <?php } ?>
</div>

设计漂亮的图片比让它工作容易得多:-p

感谢任何人提供的任何帮助。

【问题讨论】:

    标签: php wordpress image fallback featured


    【解决方案1】:

    试试这个:

    <?php 
    //define fallback image path
    $thumb = bloginfo('template_directory').'/img/news/fallback-image.jpg';
    if ( has_post_thumbnail() ) {  
    //override  fallback image if post has any thumbnail
    $thumb = get_the_post_thumbnail_url();
     }
     ?>
    
    <div class="news-hero" style="background-image: url('<?php echo $thumb;?>')">
         <div class="page-title"><h1><?php the_title(); ?></h1></div>
    </div>
    

    【讨论】:

    • 从某种意义上说,它现在正在吐出 URL 的第一部分,直到主题目录,但它只是将其作为副本放在页面的最顶部。如果我在 $thumb 回显之前包含 bloginfo('template_directory') ,我可以让它工作,但它不会拉出实际的特色图像。
    【解决方案2】:

    由于某种原因,以上将模板目录生成为页面上的纯文本。如果我回显$thumb = bloginfo('template_directory').'/img/news/fallback-image.jpg';,它将显示正确的 URL。

    但是,当作为背景图像中的 URL &lt;div class="news-hero" style="background-image: url('&lt;?php echo $thumb;?&gt;')"&gt; 回调时,它不起作用。

    当我将 $thumb = bloginfo('template_directory') 更改为 $thumb = get_template_directory_uri() 时,一切正常。不知道为什么我会相信他们会做同样的事情。 (bloginfo('template_directory') 会执行 get_template_directory_uri)。

    但它起作用了,所以我很好......

    【讨论】:

      猜你喜欢
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多