wordpress 加速主题的静态资源

wordpress 加速主题的静态资源(固定的CSS、JS和图片等)

wordpress 中用函数 get_stylesheet_directory_uri() 生成当前主题的 URL , 格式如 http://host/path/wp-content/themes/twentyseventeen

当前主题的静态的CSS、JS和图片等一般由当前主题指定相对路径, 一个完整的静态文件的 URL 是 get_stylesheet_directory_uri() + 这个相对路径

如果 wordpress 被假设在国外的服务器上,在国内访问还是比较慢的,如果能把这些静态文件放在国内的服务器上,网站速度就会有所提升。改变 get_stylesheet_directory_uri() 就可以实现这个目的。

这个函数在 wp-includes/theme.php 文件的 194 行左右,wordpress4.7

这是一个比较笨的办法,这样当从中国浏览 wordpress 时,静态文件从又拍云上加速,当从国外浏览时从原站加载静态文件

1. 替换该函数的 return 并加入下行

	$ip_china = '/china-ip.json';
	$cdn_china = '//yisuo.b0.upaiyun.com/wp-content/themes/';
	$ip_remote = $_SERVER["REMOTE_ADDR"]; 
	$path_themes = apply_filters( 'stylesheet_directory_uri', $stylesheet_dir_uri, $stylesheet, $theme_root_uri );
	if(check_is_china_ip($ip_remote, $ip_china)) $path_themes = $cdn_china . $stylesheet;

	/**
	 * Filters the stylesheet directory URI.
	 *
	 * @since 1.5.0
	 *
	 * @param string $stylesheet_dir_uri Stylesheet directory URI.
	 * @param string $stylesheet         Name of the activated theme's directory.
	 * @param string $theme_root_uri     Themes root URI.
	 */
	return $path_themes;
	


    

2. 在 wp-includes/theme.php 文件的最后一行加入这个函数
    
	
# ****** 从json格式数据中检测IP是否来自中国
function check_is_china_ip($ip, $ipjson){
    $ip_addr = explode('.', $ip);
    if(count($ip_addr) < 4) return false;
    $a1 = (int)$ip_addr[0];
    $a2 = (int)$ip_addr[1];
    $a3 = (int)$ip_addr[2];
    $a4 = (int)$ip_addr[3];
    $s_china = file_get_contents($ipjson);
    $tb_china = json_decode($s_china, 1);
    unset($s_china);
    if(!isset($tb_china[$a1][$a2]) || count($tb_china[$a1][$a2]) == 0) return false;
    $a = $a3 * 256 + $a4;
    foreach($tb_china[$a1][$a2] as $d){
        if($a >= $d['s'] && $a <= $d['e']){
            return true;
        }
    }
    return false;
}



3. 文件修改完毕,相关的 IP 库放在网站的根目录下,解压后文件不到 400 KB

	http://pan.baidu.com/s/1gfcfn95




转载于:https://www.cnblogs.com/yisuo/p/8811048.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值