# 使用WebP Cloud Services将Gravatar头像替换为WebP格式

- Link: https://duetg.com/2023/10/replace-gravatar-to-webp-format-using-webp-cloud-services/
- Published: 2023-10-02T18:33:02+08:00
- Author: DuetG

[WebP Cloud Services](https://webp.se/)是一个创业服务型公司，提供付费API将图片转换
成WebP格式供用户使用。除了收费服务外，他们也有免费账户可供选择体验，并且还提供免费
的公共服务：将[Gravatar](https://gravatar.com/)以及[GitHub](https://github.com/)
头像转换成WebP格式。

将头像替换成WebP格式除了能够加快图片加载的速度外，更重要的还是WebP Cloud Services
的服务器在大陆范围能够被访问。这样一来就不会再出现直连无法显示头像的问题，加载网站
的浏览器进度条也能够立即结束。

根据[官方文档](https://docs.webp.se/public-services/gravatar/)给出的指南，可以在
Wordpress主题的 functions.php 最下方添加钩子函数，实现在加载网站的时候将Gravatar
的 `https://www.gravatar.com/avatar/:hash` 转换成他们自己的 `https://gravatar.webp.
se/avatar/:hash`

代码如下

    ```php
    function use_webp_public_service($avatar) {
    	$avatar = str_replace(array("www.gravatar.com", "0.gravatar.com", "1.gravatar.com", "2.gravatar.com"), "secure.gravatar.com", $avatar);
        $avatar = str_replace("https://secure.gravatar.com", "https://gravatar.webp.se", $avatar);
    	return $avatar;
    }
    add_filter('get_avatar', 'use_webp_public_service');
    ```

由于给主题开了自动更新，所以一开始我选择了使用子主题来增加这个函数，这样就不担心
主题更新的时候把修改的内容覆盖掉了。但缺点是假如想换其他的主题，就还要再做一个对应
的子主题，这样实在是太麻烦了。

当然现在Wordpress有允许你执行代码片段的插件（如[Code Snippets](https://wordpress.org/plugins/code-snippets/)），
但倘若只是为了这一个功能安装如此重量级的插件又觉得有些得不偿失了。于是还是把这个
功能做成一个简单的插件来的更方便一些。本身代码也不多，更不需要更新什么，所以也就
不选择发布到Wordpress.org了，需要的话可以在下方下载自行安装。

~考虑回头要不注册个免费账户，把Blog的图片也接入WebP Cloud Services吧。~

~更新：已经在Blog上启用了。用起来也很简单，GitHub账号登录就可完成注册。官方为Wordpress
[提供了插件](https://github.com/webp-sh/wordpress-plugin-webp-cloud)，并且在插件
的页面上有详细的使用说明，按图索骥便可完成。如果是想通过Nginx来实现的话，也可以在
server 块中添加用来替换图片地址的代码~

    ```language-nginx
    #把yyets.dmesg.app替换为你的原网址，vz4w427.webp.ee替换为webp.se提供给你的代理地址
    location / {
        sub_filter_once off;
        sub_filter_types text/html;
        sub_filter  '<img src="https://yyets.dmesg.app/' '<img src="https://vz4w427.webp.ee/';
        sub_filter  '<img src=https://yyets.dmesg.app/' '<img src=https://vz4w427.webp.ee/';

        sub_filter  '<img src="/' '<img src="https://vz4w427.webp.ee/';
    }
    ```

再更新：鉴于官方的Wordpress插件不能加速文章的特色图片（外加自行修改无果），于是找到
了WebP Cloud Services后端的开源代码WebP Server Go，自行在服务器上部署，这样一来所有
图片就都自动变成WebP了。
