Sep 25

Google 提供了一个获取站点 favicon 的服务:

http://www.google.com/s2/favicons?domain=

但是天朝,Google 不稳定,所以需要把这些站点图标缓存到本地,以下:


//从URL中提取域名函数
function get_domain($url) {
/*
Author : Ayush
URL : http://Webgarb.com
*/
    $url = explode('/', str_replace('www.', '', str_replace('http://', '', $url)));
    return $url[0];
}

function getFavicon($var){
    $cache_days = 30; //图标缓存多少天
    $linkdomain = get_domain($var);
    $favicon_cache_dir = ABSPATH.'wp-content'.DIRECTORY_SEPARATOR.'plugins'.DIRECTORY_SEPARATOR.'favicon_cache';
    $favicon_url = 'https://www.quakemachinex.com/blog/wp-content/plugins/favicon_cache/'.$linkdomain.'.png';
    $fp = fopen ($favicon_cache_dir.'/'.$linkdomain.'.png', 'r');
    $favicon_create_time = filectime($favicon_cache_dir.'/'.$linkdomain.'.png');
    $time_now = date("Y-m-d H:i:s");
    $favicon_stay_days = (strtotime($time_now)-strtotime(date("Y-m-d H:i:s",$favicon_create_time)))/86400;
    $favicon_stay_days = floor($favicon_stay_days);

    if ($fp && $favicon_stay_days < $cache_days) {
        return $favicon_url;
     } else {
        $remote_favicon = file_get_contents('http://www.google.com/s2/favicons?domain='.$linkdomain);
        $local_favicon = $favicon_cache_dir.'/'.$linkdomain.'.png';
        $local_favicon_actual = fopen($local_favicon, 'w+');
	fwrite($local_favicon_actual, $remote_favicon);
	fclose($local_favicon_actual);
        return $favicon_url;
     }

}

把这个函数引用到友情链接或者 BlogRoll 都行,可以参见本站效果。

点击显示引用框
引用本文,复制粘贴...