WP静态图片资源分离

发布于 2020-05-23  27 次阅读


在主题function.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 = 'https://blog.xn--xsqp6uwvq.com'; //博客域名
    $qiniu_host = 'http://static.xn--xsqp6uwvq.com'; //CDN域名
    $cdn_exts = 'png|jpg|jpeg|gif|ico|bmp|mp4|flv'; 
    //扩展名(使用|分隔)
    $cdn_dirs = 'wp-content|wp-includes|static|svg'; 
    //目录(使用|分隔)
    $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;
    }

华风夏韵,洛水天依。