6

如何实现WordPress支持WebP格式图片上传

 2 years ago
source link: https://www.huhexian.com/13489.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如何实现WordPress支持WebP格式图片上传

青山 2021-11-2514:04:10评论1859字

WordPress默认是不支持WebP格式图片上传,我们在后台设置里面将WebP放进允许上传格式也没有反应,那么我们应该如何实现WordPress支持WebP格式图片上传呢,下面我们就来看看吧!

如何实现WordPress支持WebP格式图片上传

将下面代码添加到当前主题函数模板functions.php中。

  1. function webp_filter_mime_types( $array ) {
  2. $array['webp'] = 'image/webp';
  3. return $array;
  4. add_filter( 'mime_types', 'webp_filter_mime_types', 10, 1 );
  1. function webp_upload_mimes($existing_mimes) {
  2. $existing_mimes['webp'] = 'image/webp';
  3. return $existing_mimes;
  4. add_filter('mime_types', 'webp_upload_mimes');

虽然已经可以上传WebP格式的图片了,但在媒体列表中看不到缩略图,这是因为WordPress在用 wp_generate_attachment_metadata()函数生成图片数据时,使用了file_is_displayable_image()函数判断文件是否为图片,判断WebP图片的结果为否,因此中断了保存图片数据的操作。

该函数位于:wp-admin/includes/image.php

  1. function file_is_displayable_image( $path ) {
  2. $displayable_image_types = array( IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP, IMAGETYPE_ICO );
  3. $info = @getimagesize( $path );
  4. if ( empty( $info ) ) {
  5. $result = false;
  6. } elseif ( ! in_array( $info[2], $displayable_image_types, true ) ) {
  7. $result = false;
  8. } else {
  9. $result = true;
  10. * Filters whether the current image is displayable in the browser.
  11. * @since 2.5.0
  12. * @param bool $result Whether the image can be displayed. Default true.
  13. * @param string $path Path to the image.
  14. return apply_filters( 'file_is_displayable_image', $result, $path );

解决办法是在主题的functions.php里添加以下代码:

  1. function webp_file_is_displayable_image($result, $path) {
  2. $info = @getimagesize( $path );
  3. if($info['mime'] == 'image/webp') {
  4. $result = true;
  5. return $result;
  6. add_filter( 'file_is_displayable_image', 'webp_file_is_displayable_image', 10, 2 );
  1. function webp_is_displayable($result, $path) {
  2. if ($result === false) {
  3. $displayable_image_types = array( IMAGETYPE_WEBP );
  4. $info = @getimagesize( $path );
  5. if (empty($info)) {
  6. $result = false;
  7. } elseif (!in_array($info[2], $displayable_image_types)) {
  8. $result = false;
  9. } else {
  10. $result = true;
  11. return $result;
  12. add_filter('file_is_displayable_image', 'webp_is_displayable', 10, 2);

文本中的插图就是webp图片,虽然目前七牛、又拍云、阿里云oss、腾讯云cos等都支持WebP,不过发现苹果设备并不支持webp图片,包括IOS版的微信,这也可能是WordPress一直不支持webp图片的原因吧。

如果嫌改代码麻烦可以安装插件:Allow Webp image


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK