
正文
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






