1 Gravatar

Gravatar全称是"Globally Recognized Avatar",使用中文直译过来就是全球通用头像。是由WordPress母公司Automattic提出的全球公共头像服务。该服务可在任意支持Gravatar的网站留言时,那么会自动根据你的邮箱地址匹配头像。如果你在Gravatar网站注册了账号并且上传了头像,那么当你评论时会自动调用你所上传的头像,如果你并未在Gravatar官网注册账号以及上传头像,那么会显示一个默认的头像。

对于使用国内服务建站的WordPress朋友,使用Gravatar头像是一件痛苦的事情。由于该头像上述完全自定义并且不受国内监管,会有一些超出国内法律限制的头像图片,所以Gravatar经常会被国内q调,导致头像服务不可用。

2 Cravatar

官网:https://cravatar.cn/

Cravatar 是 Gravatar 在中国的完美替代方案,从此你可以自由的上传和分享头像。并且该头像服务的API规范与Gravatar保持100%兼容。当访客请求自己的头像时,我们会按此顺序分三级匹配头像:Cravatar->Gravatar->QQ 头像,对于博客站,这平均可以为 70% 的访客提供准确的头像。

总的来说,Cravatar在100%兼容Gravatar的同时还有以下优势:

  • 更快的速度:服务完全架设并运行在中国大陆境内,提供毫秒级的响应速度

  • 更高的稳定性:所有头像经人工审核确保不会出现违规内容,也就不会出现时不时访问不了的情况

  • 更高的头像展现率:在自有头像库的基础上囊括了Gravatar和QQ的头像库,可谓集天下之大成

3 在自己的网站中集成Cravatar

文档地址:https://cravatar.cn/developers/for-wordpress

在 WordPress 集成 Cravatar 头像服务,首先将以下代码加入你的插件或主题的 functions.php 里即可:

if ( ! function_exists( 'get_cravatar_url' ) ) {
    /**
     * 替换 Gravatar 头像为 Cravatar 头像
     *
     * Cravatar 是 Gravatar 在中国的完美替代方案,你可以在 https://cravatar.cn 更新你的头像
     */
    function get_cravatar_url( $url ) {
        $sources = array(
            'www.gravatar.com',
            '0.gravatar.com',
            '1.gravatar.com',
            '2.gravatar.com',
            'secure.gravatar.com',
            'cn.gravatar.com',
            'gravatar.com',
        );
        return str_replace( $sources, 'cravatar.cn', $url );
    }
    add_filter( 'um_user_avatar_url_filter', 'get_cravatar_url', 1 );
    add_filter( 'bp_gravatar_url', 'get_cravatar_url', 1 );
    add_filter( 'get_avatar_url', 'get_cravatar_url', 1 );
}
if ( ! function_exists( 'set_defaults_for_cravatar' ) ) {
    /**
     * 替换 WordPress 讨论设置中的默认头像
     */
    function set_defaults_for_cravatar( $avatar_defaults ) {
        $avatar_defaults['gravatar_default'] = 'Cravatar 标志';
        return $avatar_defaults;
    }
    add_filter( 'avatar_defaults', 'set_defaults_for_cravatar', 1 );
}
if ( ! function_exists( 'set_user_profile_picture_for_cravatar' ) ) {
    /**
     * 替换个人资料卡中的头像上传地址
     */
    function set_user_profile_picture_for_cravatar() {
        return '<a href="https://cravatar.cn" target="_blank">您可以在 Cravatar 修改您的资料图片</a>';
    }
    add_filter( 'user_profile_picture_description', 'set_user_profile_picture_for_cravatar', 1 );
}

然后在WordPress后台-设置-讨论的头像中勾选Cravatar,点击保存更改即可。

WordPress – 使用Cravatar替换Gravatar提供头像服务-StubbornHuang Blog

如果你原始主题中使用了默认的自定义头像,需要找到相关函数去掉自定义头像函数,一般是在get_avatar添加filter,例如:

add_filter( 'get_avatar' , 'customize_avatar' , 1 , 5 );

把类似这种函数定义去掉即可使用Cravatar头像了。