
在国内访问 Gravatar 的头像服务器速度慢甚至无法显示,这是 WordPress 用户普遍遇到的问题。本文将教你如何使用反代 CDN 替换 Gravatar,让评论头像重新显示,并附带代码讲解,适合 Astra 等所有主题使用。
🧩 问题背景
WordPress 默认使用 gravatar.com 加载头像,但这个域名在国内常年访问困难,因此评论区经常看不到访客头像。
🛠️ 解决方案:使用国内反代服务
我们通过 WordPress 的 get_avatar_url 过滤器,把默认的 Gravatar 头像链接替换为国内可访问的 CDN。
✅ 推荐使用的国内 Gravatar 镜像地址(任选一个):
| 镜像来源 | 地址示例 |
|---|---|
| Cravatar | https://cravatar.cn/avatar/ |
| Geekzu CDN | https://sdn.geekzu.org/avatar/ |
| V2EX CDN | https://gravatar.loli.net/avatar/(不稳定) |
建议优先使用 Cravatar,更快、更稳定。
📦 实现代码
将以下代码加入你主题或子主题的 functions.php 中:
add_filter('get_avatar_url', 'custom_gravatar_url', 10, 3);
function custom_gravatar_url($url, $id_or_email, $args) {
$cdn = 'https://cravatar.cn/avatar/'; // 推荐使用 cravatar.cn,更稳定。
return preg_replace('#https?://[^\s]*gravatar\.com/avatar/#', $cdn, $url);
}
🔍 正则替换说明
这一行代码:
return preg_replace('#https?://([a-z0-9]+\.)*gravatar\.com/avatar/#', $cdn, $url);
可以匹配各种头像地址形式,包括:
https://secure.gravatar.com/avatar/http://gravatar.com/avatar/https://0.gravatar.com/avatar/https://cn.gravatar.com/avatar/
并统一替换为你指定的 CDN 地址。
🚫 遇到头像缓存不更新?
Gravatar 的头像是根据邮箱 MD5 哈希生成的链接,服务器会缓存图片。你可能在 Gravatar 官网 更新头像后,还看的是旧图。
🔁 解决方法:
给头像链接加时间戳或版本参数:
$cdn = 'https://cravatar.cn/avatar/';
$timestamp = time();
return preg_replace('#https?://([a-z0-9]+\.)*gravatar\.com/avatar/#', $cdn, $url) . '&v=' . $timestamp;
⚠️ 注意:这样每次都强制刷新头像,可能增加加载时间,建议只在调试时使用。
🎨 延伸:如何隐藏 Astra 主题中的“作者”信息
Astra 默认在文章底部显示作者信息,如果你不想让它出现,可加入以下代码隐藏它:
add_action( 'wp', 'remove_astra_post_author' );
function remove_astra_post_author() {
if ( ! is_single() ) {
remove_action( 'astra_entry_header', 'astra_post_author', 10 );
remove_action( 'astra_post_footer', 'astra_post_author', 10 );
}
}
💡 其它建议
- 子主题编辑方式推荐:使用 FTP 或 SFTP 修改
functions.php文件,避免后台编辑器保存不了。 - 头像不显示请检查:
- 清理 WordPress 缓存插件
- 浏览器缓存
- 检查头像 URL 是否已替换
✅ 最终效果
头像将从如下地址加载,国内访问无压力:
https://cravatar.cn/avatar/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx