Wordpress 缩略图作为背景图像,默认后备

时间:2021-02-24 00:17:02

标签: php wordpress

我是 php 新手。开发 WordPress 网站。

我想在每个帖子/页面上提取特色图片用作英雄背景图片。如果没有特色图片,我想使用默认图片。

我发现可以单独执行上述每个操作的工作代码,但不确定如何组合它们。

精选图片作为背景图片:

<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
<div id="post" class="hero-image" style="background-image: url('<?php echo $thumb['0'];?>')">
</div>

后备默认图像:

    <?php if ( has_post_thumbnail() ) {
    the_post_thumbnail( 'full' );
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/img/default-img.jpg" alt="<?php the_title(); ?>" />
<?php } ?>

编辑:我是这样做的:

<?php if ( has_post_thumbnail() ) { ?>
    <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?>
    <div class="hero-image" style="background-image: url('<?php echo $thumb['0'];?>')"></div>
<?php } else { ?>
    <div class="hero-image" style="background-image: url('<?php bloginfo('template_directory'); ?>/img/default-img.jpg') "></div>
<?php } ?>

2 个答案:

答案 0 :(得分:0)

这就是方法。

<figure>
  <?php if (has_post_thumbnail()) { ?>
    <?php echo wp_get_attachment_image(get_post_thumbnail_id($post->ID), 
   'full'); ?>
 <?php } else { ?>
    <img src="<?php echo get_stylesheet_directory_uri() 
    .'/components/assets/images/blog-placeholder.png'; ?>">
 <?php } ?>
</figure>

答案 1 :(得分:0)

我会创建一个包含所有逻辑的函数,然后只传入帖子 ID。将该函数添加到您的 functions.php 文件中,然后在您的页面中使用它。

<?php 
function get_feat_image_or_default($id=false){
$path = "https://picsum.photos/800";
if($id){
    $path = get_the_post_thumbnail_url(id,"large") ?: $path;
}
return $path;  
}
// Then call it like this:
echo ?> <img src="<?= get_feat_image_or_default($post->ID); ?>" />
相关问题