完美替换所有的Google字体、谷歌JS公用库、Gravatar头像为geekzu资源的wordpress插件

参考了好几个插件的代码,总觉得不够精炼,于是把自认为给力的插件给码出来。下面贴上源代码:

if (is_admin()) {// init -> wp_loaded -> admin_menu -> admin_init -> wp -> admin_enqueue_scripts -> admin_head
    $action = 'admin_init';
} elseif (in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'))) {
    $action = 'wp_loaded';
} else { // init -> wp_loaded -> wp -> template_redirect -> get_header -> wp_enqueue_scripts -> wp_head
    $action = 'template_redirect';
}
function cdn_callback($buffer) {
    // Google前端库
    $buffer = str_replace('//gapis.geekzu.org/ajax/', '//gapis.geekzu.org/ajax/', $buffer);
    // Gravatar全球头像
    $buffer = preg_replace('/\/\/\w+.gravatar.com\/avatar\//', '//sdn.geekzu.org/avatar/', $buffer);
    // 谷歌字体库(Google Fonts)
    $buffer = str_replace('//fonts.geekzu.org', '//fonts.geekzu.org', $buffer);
    // 字体文件(Google Fonts)
    $buffer = str_replace('//gapis.geekzu.org/g-fonts/', '//gapis.geekzu.org/g-fonts/', $buffer);
    $buffer = str_replace('//gapis.geekzu.org/g-themes/', '//gapis.geekzu.org/g-themes/', $buffer);
    return $buffer;
}
function buffer_start() {
    ob_start("cdn_callback");
}
function buffer_end() {
    ob_end_flush();
}
add_action($action, 'buffer_start');
add_action('shutdown', 'buffer_end');

上面的代码就是这么简单。