以下是不用插件实现CDN静态资源加速的完整代码,可直接复制到WordPress主题的functions.php文件中使用。
基础版本代码
/**
* WordPress静态文件CDN加速
* 将本地静态资源替换为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 = 'https://www.yourdomain.com'; // 你的博客域名
$qiniu_host = 'https://cdn.yourdomain.com'; // CDN加速域名
$cdn_exts = 'css|js|png|jpg|jpeg|gif|ico|svg|webp|bmp|tiff'; // 扩展名(使用|分隔)
$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加速增强版
* 支持多CDN、排除特定文件、HTTPS兼容
*/
if (!is_admin() && !defined('DOING_AJAX')) {
add_action('template_redirect', 'cdn_ob_start', 1);
function cdn_ob_start() {
ob_start('cdn_resource_replace');
}
function cdn_resource_replace($html) {
// 配置信息
$cdn_config = array(
'local_host' => array('https://www.yourdomain.com', 'http://www.yourdomain.com'),
'cdn_host' => 'https://cdn.yourdomain.com', // CDN域名
'file_exts' => 'css|js|png|jpg|jpeg|gif|ico|svg|webp|bmp|tiff|woff|woff2|ttf|eot|otf',
'directories' => 'wp-content|wp-includes',
'exclude_files' => array('admin-ajax.php', 'admin-bar.css') // 排除的文件
);
// 处理每个本地域名
foreach ($cdn_config['local_host'] as $local_host) {
$cdn_dirs = str_replace('-', '\-', $cdn_config['directories']);
if (!empty($cdn_dirs)) {
$regex = '/' . str_replace('/', '\/', $local_host) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_config['file_exts'] . '))([\"\\\'\s\?]{1})/';
} else {
$regex = '/' . str_replace('/', '\/', $local_host) . '\/([^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_config['file_exts'] . '))([\"\\\'\s\?]{1})/';
}
// 排除特定文件
if (!empty($cdn_config['exclude_files'])) {
$html = preg_replace_callback($regex, function($matches) use ($cdn_config, $cdn_host) {
foreach ($cdn_config['exclude_files'] as $exclude) {
if (strpos($matches[1], $exclude) !== false) {
return $matches[0]; // 返回原始URL
}
}
return $cdn_config['cdn_host'] . '/' . $matches[1] . $matches[4];
}, $html);
} else {
$html = preg_replace($regex, $cdn_config['cdn_host'] . '/$1$4', $html);
}
}
return $html;
}
}
多CDN版本代码(支持不同文件类型使用不同CDN)
/**
* WordPress多CDN静态资源加速
* 不同文件类型可使用不同CDN服务
*/
if (!is_admin()) {
add_action('wp_loaded', 'multi_cdn_ob_start');
function multi_cdn_ob_start() {
ob_start('multi_cdn_replace');
}
function multi_cdn_replace($html) {
$local_host = 'https://www.yourdomain.com';
// 多CDN配置
$cdn_configs = array(
array(
'exts' => 'css|js',
'dirs' => 'wp-content|wp-includes',
'cdn_url' => 'https://js-cdn.yourdomain.com'
),
array(
'exts' => 'png|jpg|jpeg|gif|ico|svg|webp',
'dirs' => 'wp-content|wp-includes',
'cdn_url' => 'https://img-cdn.yourdomain.com'
),
array(
'exts' => 'woff|woff2|ttf|eot|otf',
'dirs' => 'wp-content|wp-includes',
'cdn_url' => 'https://font-cdn.yourdomain.com'
)
);
foreach ($cdn_configs as $config) {
$cdn_dirs = str_replace('-', '\-', $config['dirs']);
if (!empty($cdn_dirs)) {
$regex = '/' . str_replace('/', '\/', $local_host) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $config['exts'] . '))([\"\\\'\s\?]{1})/';
} else {
$regex = '/' . str_replace('/', '\/', $local_host) . '\/([^\s\?\\\'\"\;\>\<]{1,}.(' . $config['exts'] . '))([\"\\\'\s\?]{1})/';
}
$html = preg_replace($regex, $config['cdn_url'] . '/$1$4', $html);
}
return $html;
}
}
简单配置版本(新手友好)
/**
* CDN静态资源加速 - 简单配置版
* 只需要修改下面的配置即可使用
*/
// 配置开始
define('CDN_LOCAL_HOST', 'https://www.yourdomain.com'); // 你的网站域名
define('CDN_HOST', 'https://cdn.yourdomain.com'); // CDN域名
// 配置结束
if (!is_admin()) {
add_action('wp_loaded', 'simple_cdn_start');
function simple_cdn_start() {
ob_start('simple_cdn_replace');
}
function simple_cdn_replace($html) {
$local_host = CDN_LOCAL_HOST;
$qiniu_host = CDN_HOST;
$cdn_exts = 'css|js|png|jpg|jpeg|gif|ico|svg|webp|woff|woff2';
$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);
}
return $html;
}
}
使用说明
1. 基本配置
- 将代码中的
https://www.yourdomain.com替换为你的实际域名 - 将
https://cdn.yourdomain.com替换为你的CDN域名 - 将代码添加到主题的
functions.php文件末尾
2. 扩展名说明
- 基本格式:
css|js|png|jpg|jpeg|gif|ico - 增强格式: 添加了
svg|webp|bmp|tiff|woff|woff2|ttf|eot|otf - 可根据需要自行增减文件类型
3. 目录说明
wp-content: 主题、插件、上传文件目录wp-includes: WordPress核心文件目录- 可添加其他目录,如自定义上传目录
4. 注意事项
- CDN配置: 确保CDN已正确配置,能够从源站拉取资源
- SSL证书: 如果使用HTTPS,确保CDN支持SSL
- 缓存问题: 修改代码后,清除浏览器和CDN缓存
- 测试方法: 查看网页源代码,检查静态资源URL是否已替换为CDN地址
5. 调试代码
如果需要调试,可以添加以下代码:
/**
* CDN替换调试函数
*/
function debug_cdn_replace($html) {
$patterns = array(
'/https:\/\/www\.yourdomain\.com\/wp-content/',
'/https:\/\/www\.yourdomain\.com\/wp-includes/'
);
$replacements = array(
'https://cdn.yourdomain.com/wp-content',
'https://cdn.yourdomain.com/wp-includes'
);
$new_html = preg_replace($patterns, $replacements, $html);
// 记录替换数量
$count = 0;
foreach ($patterns as $pattern) {
$count += preg_match_all($pattern, $html);
}
error_log("CDN替换完成,共替换 {$count} 个资源链接");
return $new_html;
}
常见问题解决方案
1. 替换不生效
- 检查代码是否添加到
functions.php正确位置 - 检查域名配置是否正确
- 清除所有缓存(浏览器、插件、CDN)
2. 部分资源未替换
- 检查文件扩展名是否包含在配置中
- 检查资源URL格式是否匹配
- 某些插件可能使用不同的URL生成方式
3. 网站显示异常
- 暂时禁用CDN替换代码
- 检查CDN是否正常获取资源
- 检查HTTPS证书是否有效
4. 性能优化建议
- 使用对象存储+CDN组合
- 合理设置CDN缓存时间
- 对JS/CSS进行合并压缩
- 使用WebP等现代图片格式
替代方案
如果代码替换方式不满足需求,还可以考虑以下方案:
- 使用CDN插件: WP Rocket、W3 Total Cache、Autoptimize等
- Nginx/Apache规则: 在服务器层面进行URL重写
- DNS CNAME: 将静态资源子域名解析到CDN
- 对象存储: 直接使用云存储服务
总结
这段代码提供了一种轻量级的WordPress CDN加速方案,适合不想安装额外插件的用户。通过输出缓冲和正则表达式替换,可以快速将本地静态资源替换为CDN地址,提升网站加载速度。
重要提示: 在生产环境使用前,请先在测试环境验证功能正常,并做好网站备份。


湘公网安备43020002000238