将WordPress网站代码压缩为一行!

好久没鼓捣WordPress网站优化加速了,其实上了几个主要的手段,再进行其他的优化加速措施,效果已经不会太明显了。不过很多朋友估计和老白刚入坑一样,追求极致的WordPress网站访问速度,今天就给大家分享一个通过压缩WordPress网站来实现优化加速的方法,不用安装任何插件,纯代码实现。

Wordpress 网站压缩前端html代码

1.WordPress网站压缩代码

网站插件安装越多,负载越大,访问速度自然快不起来,因此我们的口号是“能不装,就不装

将以下代码放到网站当前使用主题根目录下的functions.php文件即可

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("nn", "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;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');

2.效果展示

不同的网站会有不同的效果,节约了20也很不错了

将WordPress网站代码压缩为一行!

3.注意事项

另外对于某些JS文件,压缩容易出问题的

<!--wp-compress-html--><!--wp-compress-html no compression-->
此处代码不会被压缩,主要是避免压缩带来的错误,比如 JS 错误
<!--wp-compress-html no compression--><!--wp-compress-html-->

网站文章中有时候也需要插入代码,一篇文章需要插入几段代码了,如果文章中插入的代码也被压缩,是很影响用户阅读体验的,所有我们也要进行一下处理,同样将以下代码放入functions.php文件里面。

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");

除了这种代码压缩以外,还可以试试服务器端的nginx压缩