让 WordPress 支持 WebP格式图片
让WordPress 支持 WebP格式图片 section WordPress 默认不支持WebP格式图片上…
让WordPress 支持 WebP格式图片
section
WordPress 默认不支持WebP格式图片上传,将下面代码添加到当前主题函数模板functions.php中,即可解决上传问题。
function webp_filter_mime_types( $array ) {
$array['webp'] = 'image/webp';
return $array;
}
add_filter( 'mime_types', 'webp_filter_mime_types', 10, 1 );section
另一段类似的代码
function webp_upload_mimes($existing_mimes) {
$existing_mimes['webp'] = 'image/webp';
return $existing_mimes;
}
add_filter('mime_types', 'webp_upload_mimes');
section
虽然已经可以上传WebP格式的图片了,但在媒体列表中看不到缩略图,这是因为WordPress在用 wp_generate_attachment_metadata()函数生成图片数据时,使用了file_is_displayable_image()函数判断文件是否为图片,判断WebP图片的结果为否,因此中断了保存图片数据的操作。
该函数位于:wp-admin/includes/image.php
function file_is_displayable_image( $path ) {
$displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO );
$info = @getimagesize( $path );
if ( empty( $info ) ) {
$result = false;
} elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
$result = false;
} else {
$result = true;
}
/**
* Filters whether the current image is displayable in the browser.
*
* @since 2.5.0
*
* @param bool $result Whether the image can be displayed. Default true.
* @param string $path Path to the image.
*/
return apply_filters( 'file_is_displayable_image', $result, $path );
}
section
解决办法是在主题的functions.php里添加以下代码:
function webp_file_is_displayable_image($result, $path) {
$info = @getimagesize( $path );
if($info['mime'] == 'image/webp') {
$result = true;
}
return $result;
}
add_filter( 'file_is_displayable_image', 'webp_file_is_displayable_image', 10, 2 );function webp_is_displayable($result, $path) {
if ($result === false) {
$displayable_image_types = array( IMAGETYPE_WEBP );
$info = @getimagesize( $path );
if (empty($info)) {
$result = false;
} elseif (!in_array($info[2], $displayable_image_types)) {
$result = false;
} else {
$result = true;
}
}
return $result;
}
add_filter('file_is_displayable_image', 'webp_is_displayable', 10, 2);
section
本文中的插图就是webp图片,以目前的网络速度使用webp图片并不完全为了加载快,而是当图片很多时webp图片优势就明显了,可以减少三分一以上的空间占用。虽然目前七牛、又拍云、阿里云oss、腾讯云cos等都支持WebP,可惜之前苹果设备不支持webp图片,这也可能是WordPress一直不支持webp图片的原因吧。
不过新版Safari和微信已支持webp图片,是个好消息。
嫌改代码麻烦可以安装插件:Allow Webp image
代码源自:
https://mariushosting.com/how-to-upload-webp-files-on-wordpress/
https://www.beizigen.com/2205.html
本文的方法已过时,目前WP已默认支持webp。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。

还没有任何评论,赶紧来占个楼吧!