记录一些常用的函数和瞎折腾的过程……

非插件实现wordpress七牛CDN加速

提醒:本文最后更新于 2354 天前,文中所描述的信息可能已发生改变,请谨慎使用。

wordpress要使用七牛的CDN,除了使用插件,还可以使用纯代码实现,告别插件的臃肿,往functions.php添加代码即刻实现相应功能。

// 静态资源使用七牛CDN
function Qiniu_cdn(){
    ob_start( 'Qiniu_cdn_replace' );
}
add_action( 'template_redirect', 'Qiniu_cdn' );
function Qiniu_cdn_replace( $code ){
    $cdn_exts = 'png|jpg|jpeg|gif|bmp';
    $cdn_dirs = str_replace( '-', '\-', 'wp-content|wp-includes' );
    $regex = '/' . str_replace( '/', '\/', site_url() ) . '\/((' . $cdn_dirs . ')\/[^\s\?\\\'\"\;\>\<]{1,}.(' . $cdn_exts . '))([\"\\\'\s\?]{1})/';
    return preg_replace( $regex, '//七牛的链接/$1$4', $code );
}

或者这段代码也行,在上面的代码上稍有修改:

//静态资源使用七牛CDN
if ( !is_admin() ) {
    add_action('wp_loaded','cdn_ob_start');
    function cdn_ob_start() {
        ob_start('cdn_replace');
    }
    function cdn_replace($html) {
        $local_host = 'http://www.yourblog.com'; //博客域名
        $qiniu_host = 'http://cnd.clouddn.com'; //CDN域名
        $cdn_exts   = 'js|css|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;
    }
}

还有个更简单的方法,直接进行替换:

//替换加速域名
function COS_ob_start() {
    ob_start( 'COS_cdn_replace' );
}
add_action( 'template_redirect', 'COS_ob_start' );
function COS_cdn_replace( $html ) {
    return str_replace( 'http://www.psay.cn/wp-content', 'http://files.psay.cn', $html );
}