如何在模板中显示缩放的特色图像?

时间:2018-07-19 作者:Bikram

我需要在我的主题模板上的所需位置显示帖子特色图像。同时,我需要它的宽度为300px,高度自适应。

我应该向模板中添加什么代码?

2 个回复
最合适的回答,由SO网友:Shibi 整理而成

可以使用创建自定义大小的图像add_image_size() 在函数中。php

function add_custom_size_images() {
    // Add image size width 300 with unlimited height.
    add_image_size( \'featured-image-300\', 300 );
}
add_action( \'after_setup_theme\', \'add_custom_size_images\' );
并在模板中获取创建时使用的大小the_post_thumbnail()

the_post_thumbnail( \'featured-image-300\' );
Notice: 如果你想让它处理你已经上传的旧图像,你需要重新生成缩略图。这里有一些插件。

例如插件https://wordpress.org/plugins/regenerate-thumbnails/

SO网友:Guillermo Carone

如果希望图像的宽度固定,高度改变,则应考虑创建div并将图像添加为背景中的封面,否则将导致图像变形。

这是代码。你也可以看到它在这里工作https://codepen.io/guillermo-carone/pen/zLKQON

<style>
.post_snap {
    width: 300px;
    height: 75vh;
}
</style>

<div class="post_snap" style="background: url(http://mirlostudio.com/mission-3/wp-content/uploads/sites/28/2016/07/Look-Up-Architecture-17.jpg) no-repeat center; background-size: cover;">

结束

相关推荐

Custom templates vs page-slug

我目前一直在使用slug来设置页面模板,使用普通的层次结构例如,如果我想更改的页面模板http://www.example.com/about-us, 我会编辑关于我们的页面。php如果客户端要去更改页面slug,它将不再加载正确的模板。在WordPress后端使用“自定义模板”下拉列表是否更好?就这一点而言,最佳做法是什么?非常感谢