Gravatar,是全球通用頭像服務,服務器在國外,所以 Gravatar 的頭像載入會影響網站速度。這時我們就需要把 Gravatar 頭像緩存在本地,方法很簡單,不需要任何 WordPress 插件,只需在 functions.php 中插入代碼即可。
首先,在網站的根目錄下創建一個文件夾,名字取為 「avatar」,並右鍵-屬性,設置權限為 「777」,然後進入 WP 後台 – 主題 – 編輯,找到 functions.php ,在裏面插入如下代碼:
/* Gavatar 頭像緩存 */
function get_cavatar($source) {
$time = 1209600; //The time of cache(seconds)
preg_match(『/avatar/([a-z0-9]+)?s=(d+)/』,$source,$tmp);
$abs = ABSPATH.』avatar/』.$tmp[1].』.jpg』;
$url = get_bloginfo(『wpurl』).』/avatar/』.$tmp[1].』.jpg』;
$default = get_bloginfo(『wpurl』).』/avatar/』.'default.jpg』;
if (!is_file($abs)||(time()-filemtime($abs))>$time){
copy(『http://www.gravatar.com/avatar/』.$tmp[1].』?s=64&d=』.$default.』&r=G』,$abs);
}
if (filesize($abs)<500) { copy($default,$abs); }
return 『<img alt="" src="』.$url.』" width="』.$tmp[2].』" height="』.$tmp[2].』" />』;
}
}
add_filter(『get_avatar』,'get_cavatar』);
function get_cavatar($source) {
$time = 1209600; //The time of cache(seconds)
preg_match(『/avatar/([a-z0-9]+)?s=(d+)/』,$source,$tmp);
$abs = ABSPATH.』avatar/』.$tmp[1].』.jpg』;
$url = get_bloginfo(『wpurl』).』/avatar/』.$tmp[1].』.jpg』;
$default = get_bloginfo(『wpurl』).』/avatar/』.'default.jpg』;
if (!is_file($abs)||(time()-filemtime($abs))>$time){
copy(『http://www.gravatar.com/avatar/』.$tmp[1].』?s=64&d=』.$default.』&r=G』,$abs);
}
if (filesize($abs)<500) { copy($default,$abs); }
return 『<img alt="" src="』.$url.』" width="』.$tmp[2].』" height="』.$tmp[2].』" />』;
}
}
add_filter(『get_avatar』,'get_cavatar』);
最後保存即可,這樣網站有頭像的地方都會自動替換成本地的緩存頭像咯。