WebP 是 Google 早在 2010 年就提出的一种新的图片压缩格式,相比 JPEG 和 PNG 格式的图片,文件大小平均小了 30% 左右,从而使得网站的速度更快,使用的带宽也更少,根据 caniuse 网站的统计,目前所有现代浏览器基本都支持 WebP 了。
值得注意的是,WordPress 从 5.8 版本开始,就可以像上传 JPEG 或者 PNG 图片一样,在 WordPress 直接上传 WebP 图片。所以以下教程是针对5.8以下版本的
将下面代码添加到当前主题函数模板functions.php中,即可解决上传问题。
function webp_filter_mime_types( $array ) {$array['webp'] = 'image/webp';return $array;}add_filter( 'mime_types', 'webp_filter_mime_types', 10, 1 );
function webp_upload_mimes($existing_mimes) { $existing_mimes['webp'] = 'image/webp'; return $existing_mimes;}add_filter('mime_types', 'webp_upload_mimes');
虽然已经可以上传WebP格式的图片了,但在媒体列表中看不到缩略图,这是因为WordPress在用 wp_generate_attachment_metadata()函数生成图片数据时,使用了file_is_displayable_image()函数判断文件是否为图片,判断WebP图片的结果为否,因此中断了保存图片数据的操作。
该函数位于:wp-admin/includes/image.php展开
解决办法是在主题的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);
本文来源:【 如何让 WordPress 支持 WebP格式图片】
由思享SEO博客编辑转载,仅用于参考学习,如有侵权请联系本站修改删除!