WordPress纯代码实现前端代码压缩高效提升网站加载

对于前端的代码是直接影响到百度搜索抓取效率的,如何高效的对WordPress主题前端代码进行压缩来提升网站加速呢,下面分享一段代码给大家使用,这个前端代码压缩方法可以高效优化前端访问,但是需要注意,对于部分主题是会对前端的调用动态脚本产生负面影响的,就是说可能导致功能不可用或是错误提示。

第一、实现WordPress前端代码压缩功能

//无插件压缩WordPress前端代码
function wp_compress_html(){
function wp_compress_html_main ($buffer){
$initial=strlen($buffer);
$buffer=explode("<!--wp-compress-html-->", $buffer);
$count=count ($buffer);
for ($i = 0; $i <= $count; $i++){
if (stristr($buffer[$i], '<!--wp-compress-html no compression-->')) {
$buffer[$i]=(str_replace("<!--wp-compress-html no compression-->", " ", $buffer[$i]));
} else {
$buffer[$i]=(str_replace("\t", " ", $buffer[$i]));
$buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));
$buffer[$i]=(str_replace("\n", "", $buffer[$i]));
$buffer[$i]=(str_replace("\r", "", $buffer[$i]));
while (stristr($buffer[$i], ' ')) {
$buffer[$i]=(str_replace(" ", " ", $buffer[$i]));
}
}
$buffer_out.=$buffer[$i];
}
$final=strlen($buffer_out);
$savings=($initial-$final)/$initial*100;
$savings=round($savings, 2);
$buffer_out.="\n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
return $buffer_out;
}
//WordPress后台不压缩
if ( !is_admin() ) {
ob_start("wp_compress_html_main");
}
}
add_action('init', 'wp_compress_html');
//当检测到文章内容中有代码标签时文章内容不会被压缩
function unCompress($content) {
if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) {
$content = '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;
$content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
}
return $content;
}
add_filter( "the_content", "unCompress");

将代码添加到当前主题的Functions.php文件中。

第二、不需要进行压缩的代码需要特别备注出来

<!--wp-compress-html--><!--wp-compress-html no compression-->

如果不希望被压缩的代码填写到这个里

<!--wp-compress-html no compression--><!--wp-compress-html-->

这个功能就是保护我们容易出错的代码,提供的避免问题部分出现的解决方案。

http://xzh.i3geek.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请不要用于商业用途及非法用途,否则后果自负!
3. 如果你也有好源码或者教程,可以到审核区发布,分享有金币奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"qq301.com",如遇到无法解压的请联系管理员!
资源客是一个优秀的分享资源站,本站资源均为各位友友分享而来,特殊原创会标明如有侵犯版权等可联系删除

资源客 » WordPress纯代码实现前端代码压缩高效提升网站加载