前两天知道了怎么不用插件整合CDN静态资源加速,今天就为大家分享纯代码实现整合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|jpg|jpg|jpeg|gif|ico\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’; //扩展名(使用|分隔)

$cdn_dirs = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’wp-content|wp-includes\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’; //目录(使用|分隔)

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

if ($cdn_dirs) {

$regex = \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’/\\\\\\\\\\\\\\\\\\\\\\\\\\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\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\s\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?]{1})/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’;

$html = preg_replace($regex, $qiniu_host . \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’/$1$3\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\’, $html);

}

return $html;

}

}

简单的一段代码,就能让你的 WordPress 实现静态文件 CDN 加速。当然,如果你的需求还包括加速远程图片或刷新缓存等,那么还是老老实实安装插件吧!

相关新闻

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

联系我们

151-1101-0018

在线咨询:
邮件:30115776@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
关注微信
分享本页
返回顶部