如果上传的图像尺寸较小,如何强制 WordPress 缩略图拉伸以适应


How do I force WordPress thumbnails to stretch to fit if uploaded image if it has smaller dimensions?

我网站上的用户上传的图像小于我的WordPress主题的基本缩略图尺寸。如何强制这些类型的图像垂直或水平拉伸,以便没有空白区域?

我的wp-admin>settings>media>thumbnail size设置为124px x 156px。上传的图片60px x 190px破坏网站布局。www.sharehouse.co 是测试站点。下面的代码是需要更改的内容。

<div class="post-left">
    <a href="<?php the_permalink(); ?>" <?php if ((get_option('cp_ad_image_preview') == 'yes') && (cp_get_image_url_raw($post->ID, 'large', 1) == true)) { ?>class="preview" rel="<?php echo cp_get_image_url_raw($post->ID, 'large', 1); ?>" <?php } ?>><?php if(get_post_meta($post->ID, 'images', true)) cp_single_image_legacy($post->ID, get_option('thumbnail_size_w'), get_option('thumbnail_size_h'), 'preview'); else cp_get_image_url_feat($post->ID, 'thumbnail', 'preview', 1); ?></a>                
</div>

因此,您需要做的第一件事是从WordPress创建的img HTML中删除硬编码的宽度和高度属性。它认为你应该拥有这些维度,并迫使你使用它们。

取自: https://wordpress.stackexchange.com/questions/5568/filter-to-remove-image-dimension-attributes

add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 );
function remove_thumbnail_dimensions( $html ) {
    $html = preg_replace( '/(width|height)='"'d*'"'s/', "", $html );
    return $html;
}

然后它只是CSS

.attachment img {
  width: 100%; /* scale to width of container, or whatever you want */
}