利用阿里云OSS将WordPress文章中的图片自动转为webp

WordPress用阿里云OSS插件(aliyun-oss-support)之后,可以将附件存储到OSS上面,如果需要将文章中的图片处理为webp格式呢?这样的好处就是根本不需要做图片压缩了。

可以用OSS图片处理来实现,在主题functions.php文件中或者使用Code Snippets插件添加自定义代码:

/**
 * 利用阿里云OSS将WordPress文章中的图片自动转为webp.
 * 
 * @link https://wpmore.cn/aliyun-oss-wordpress-the_content-img-webp.html
 */
function webp_converse($matches) {
  $len = substr($matches[2],(strlen($matches[2])-4));
  if( $len != 'webp' || $len != '.gif'){
    return $matches[1] . $matches['2'] . '?x-oss-process=image/auto-orient,1/quality,q_98/format,webp';
	}
}
 
function webp_converse_img($content){
  global $post;
  $content = preg_replace_callback("/(<img[^>]*src *= *[\"']?)([^\"']*)/i", 'webp_converse' , $content);
  return $content;
}
 
function is_support_webp(){
  return strstr($_SERVER['HTTP_ACCEPT'],'image/webp');
}
 
if ( is_support_webp() ){
  add_filter('the_content','webp_converse_img');
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注