如何自定义WordPress Post Thumbnails?

时间:2018-02-05 20:34:19

标签: php wordpress wordpress-theming custom-wordpress-pages

如何覆盖默认"自然" WordPress中缩略图的大小?我的functions.php和CSS无效。它使图像模糊。

Screenshot

的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; 
}  

Page-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 Dev Tools 中, 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">

1 个答案:

答案 0 :(得分:2)

更好的做法是通过方法get_the_post_thumbnail_url()使用缩略图的网址。您只需使用下一个结构,就可以制作任何自定义缩略图。确保您拥有所需分辨率的附加图像。要正确处理所有分辨率,最佳做法是使用<picture></picture>选择器。

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

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