如何自定义 WordPress Post 缩略图?

How to Customize WordPress Post Thumbnails?

如何覆盖 WordPress 中缩略图的默认 "Natural" 大小?我的 functions.php 和 CSS 不工作。它使图像模糊。

Functions.php

// Enable support for Post Thumbnails on posts and pages.
add_theme_support('post-thumbnails');
set_post_thumbnail_size( 450, 250, true );

Style.css:

/*  Featured image thumbnail */
.attachment-post-thumbnail, .size-post-thumbnail, .wp-post-image { 
    width: 450px !important; 
    height: 250px !important; 
}  

页面-blog.php(自定义博客页面):

       <article id="post-<?php the_ID(); ?>" 
    <?php post_class(); ?>>
              <h2 class=""> 
<a class="blog-title" href="<?php the_permalink(); ?>"> <?php the_title(); ?></a> </h2>
                 <div class="entry-content"> <?php 
          if ( has_post_thumbnail ) {                                            
             the_post_thumbnail();
                                     }
                               the_excerpt();   
                                                    ?> 
                                          </div>
                                     </article>

Google 开发工具 中,HTML 呈现如下所示 。请注意,它附加了默认的 150 x 150(我没有这样硬编码):

   <div class="entry-content"> 
    <img width="150" height="150" src="http://localhost:8888/wordpress/wp-content/uploads/2018/02/feature_nothavingit-150x150.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="http://localhost:8888/wordpress/wp-content/uploads/2018/02/feature_nothavingit-150x150.jpg 150w, http://localhost:8888/wordpress/wp-content/uploads/2018/02/feature_nothavingit-45x45.jpg 45w" sizes="(max-width: 150px) 100vw, 150px">

更好的做法是通过方法 get_the_post_thumbnail_url(). You just need to use the next structure and you can make any custom thumbnail. And be sure, that you have an additional image with needed resolution. For correct work on all resolutions the best practice is to use <picture></picture> 选择器使用缩略图的 url。

$thumbnail_url = get_the_post_thumbnail_url(the_ID(), 'post-thumbnails');

<div class="entry-content"> 
     <img src='<?php echo $thumbnail_url; ?>'>
</div>