首页 > 解决方案 > WordPress webp 图片预览

问题描述

我已经使用以下代码更新了 wordpress 以允许 webp 上传,

function webp_upload_mimes( $existing_mimes ) {
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}
add_filter( 'mime_types', 'webp_upload_mimes' );

效果很好,但是 webp 图像没有在媒体选择器中显示预览,如图所示

在此处输入图像描述

无论如何我可以强制 wordpress 呈现 webp 预览吗?当我的网站完成时,它可能有数百个 webp 图像,在选择时看不到它们可能是一个巨大的痛苦!

标签: phpwordpress

解决方案


2021 年 7 月更新

从 WordPress 5.8 版开始,您可以像现在使用 JPEG 或 PNG 图像一样在 WordPress 中上传和使用 WebP 图像(只要您的托管服务支持 WebP)。为您的图像切换到 WebP 格式将提高您网站的性能和网站访问者的体验。
https://make.wordpress.org/core/2021/06/07/wordpress-5-8-adds-webp-support/


我找到了在媒体管理器上显示缩略图的解决方案。您必须将以下代码添加到functions.php您的活动主题中:

//enable upload for webp image files.
function webp_upload_mimes($existing_mimes) {
    $existing_mimes['webp'] = 'image/webp';
    return $existing_mimes;
}
add_filter('mime_types', 'webp_upload_mimes');

//enable preview / thumbnail for webp image files.
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);

webp_is_displayable函数正在使用file_is_displayable_image钩子并检查文件 (on $path) 是否为webp图像文件。要检查webp图像文件,该函数使用常量IMAGETYPE_WEBP.


推荐阅读