首页 > 解决方案 > 自定义存档缩略图而不是最新帖子的缩略图(Wordpress)

问题描述

我的(类别)存档页面显示该循环中最新帖子的缩略图。现在我不希望这种情况发生,并给我的存档页面一个标准的缩略图。我怎样才能做到这一点?

在我的标题中,我有:

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

但不幸的是,这不起作用。有谁知道如何为我的存档页面设置标准缩略图,而不是显示最新帖子的缩略图?

标签: phpwordpress

解决方案


编辑:6/30/2020 -我想我误读了你的问题,所以让我添加更多细节。在档案类型页面上有许多条件标签,例如is_category()(以及其他)。你可能想要其中之一。如果 is_category() 对您的情况不够具体,您可以转到上面的链接查看所有选项。

选项1

if (is_category()) {
    $img_url = get_template_directory_uri() . '/images/bannershape.svg';
}
else {
    $img_url = get_the_post_thumbnail_url($post, 'full') ?: get_template_directory_uri() . '/images/bannershape.svg';
}
<div class="banner-image" style="background-image:url('<?= $img_url ?>');"></div>

选项#2(不那么严格)

$default_img_url = get_template_directory_uri() . '/images/bannershape.svg';
$img_url = is_singular() && ($thumb_url = get_the_post_thumbnail_url($post, 'full')) ? $thumb_url : $default_img_url;
<div class="banner-image" style="background-image:url('<?= $img_url ?>');"></div>

选项 #3 不确定,但根据您正在做的事情,您可能会接受这种单线

$img_url = get_the_post_thumbnail_url(null, 'full') ?: get_template_directory_uri() . '/images/bannershape.svg';
  • nullonget_the_post_thumbnail_url只会获取当前页面/帖子
  • get_the_post_thumbnail_url“安全地”(没有错误,通过已经为您内置的健全性检查)FALSE在未找到 $post 或 $_thumbnail_id 时返回
  • $a ?: $b速记三元$a ? $a : $b

原始答案:如果您在页面、帖子、术语等上,您可以使用以下两个函数获取原始查询对象:get_queried_object()get_queried_object_id()。这将分别为您提供当前页面/对象(或帖子、术语等)的 $object,或当前页面(/etc)的 $object_id。


推荐阅读