网络民工 发表于 2020-7-18 23:06:29

无需插件!轻松整合WordPress与CDN加速服务


在 WordPress 主题目录下的 functions.php 文件中,加入以下代码实现替换功能:
//静态文件CDN加速
if ( !is_admin() ) {
add_action('wp_loaded','yuncai_ob_start');

function yuncai_ob_start() {
ob_start('yuncai_qiniu_cdn_replace');
}
function yuncai_qiniu_cdn_replace($html){
$local_host = '博客域名'; //博客域名
$qiniu_host = 'CDN加速域名'; //CDN域名
$cdn_exts = 'css|js|png|jpg|jpeg|gif|ico'; //扩展名(使用|分隔)
$cdn_dirs = 'wp-content|wp-includes'; //目录(使用|分隔)

$cdn_dirs = str_replace('-', '\-', $cdn_dirs);

if ($cdn_dirs) {
$regex = '/' . str_replace('/', '\/', $local_host) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
$html = preg_replace($regex, $qiniu_host . '/$1$4', $html);
} else {
$regex = '/' . str_replace('/', '\/', $local_host) . '\/([^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
$html = preg_replace($regex, $qiniu_host . '/$1$3', $html);
}
return $html;
}
}简单的一段代码,就能让你的 WordPress 实现静态文件CDN加速。当然,如果你的需求还包括加速远程图片或刷新缓存等,那么还是老老实实安装插件吧!
原文链接:https://wuzuhua.cn/2018/12/17/cdjs.html




页: [1]
查看完整版本: 无需插件!轻松整合WordPress与CDN加速服务