WordPress下利用七牛云或又拍云使用WebP图片格式

WebP格式是谷歌开发的一种旨在加快图片加载速度的图片格式,体积大概为jpg格式的2/3, 如果一篇文章有多张图片,这速度提升的就不是一点半点了。

又拍云WebP图片转换https://www.upyun.com/webp.html

那么问题来了,我们手头并没有webp 格式的图片,就算有还有不支持的浏览器,这我们也得考虑。幸运的是主流图片云储存都提供了输入格式的选择,WebP 也包含在其中,只要你使用了此类云存储,那么都可以输出WebP 格式了,我们剩下要做的就是判断何时输出WebP 格式。简单的方法,可以根据 HTTP头中的accept 是否包含image/webp来判断浏览器是否支持WebP格式。

下面的代码直接加到主题 functions.php中即可

function fa_converse_webp($matches) {
    return $matches[1] . $matches['2'] . '!/format/webp';
    // 七牛把!/format/webp替换为下面的字段
    //?imageView2/2/format/webp
}

function fa_converse_webp_filter($content){
    global $post;
    $content = preg_replace_callback("/(<img[^>]*src *= *[\"']?)([^\"']*)/i", 'fa_converse_webp' , $content);
    return $content;
}

function fa_is_support_webp(){
    return strstr($_SERVER['HTTP_ACCEPT'],'image/webp');
}

if ( fa_is_support_webp() ) add_filter('the_content','fa_converse_webp_filter');

默认代码支持的是又拍云,如果你使用的是七牛则将

!/format/webp

替换为

?imageView2/2/format/webp

发表评论

68 − sixty =