WordPress纯代码实现七牛云存储加速网站

在看这边文章之前,你得会自己创建七牛云存储空间,如果不会,那这个文章对你来无用,当然,也可以学学,后期摸索着自己创建,也可以咨询我帮忙哦。

那么,我们为什么要弄七牛云存储呢?

一、七牛云存储的好处

加速网站的css、js、图片等内容,提升用户体验。

在我们运营网站时多多少少会用到图片存储,七牛云存储注册认证通过标准用户就可以得到10G的免费存储空间和免费10G的月流量,10G空间对于一般个人博客或小型站点基本上就够用了。

二、实现方法

把下面一段代码添加到主题的function.php文件中即可,注意更换代码中的域名哦

	//七牛镜像存储
	if ( !is_admin() ) {
		add_action('wp_loaded','wpbon_ob_start');
		function wpbon_ob_start() {
			ob_start('wpbon_qiniu_cdn_replace');
		}
		function wpbon_qiniu_cdn_replace($html){
			$local_host = 'https://www.xxx.com'; //你的网站域名  http或是https根据你的站点更换
			$qiniu_host = 'https://img.xxx.com'; //你的七牛域名  http或是https根据你的站点更换
			$cdn_exts   = 'png|jpg|jpeg|gif'; //扩展名(使用|分隔)
			$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;
		}
	}
温馨提示:RIPRO主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
版权提醒:除非注明,否则文章均由WPBON原创,转载请保留版权和本文链接 https://www.wpbon.com/56.html
本文标签: , ,

发表回复

提供最优质的资源集合

立即查看 了解详情