随着WordPress数据的不断增多,我们会发现 WordPress打开速度越来越慢。于是我们会想到各种的优化速度策略来解决这个问题。包括我们也有前端HTML压缩的减少页面体积的方法。当然,这个办法我们可以通过插件解决或者是通过无插件代码解决。
//压缩HTML代码 https://www.zhujipingjia.com/wpcompress-html.html
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;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');
当然,我们也可以使用 一些 WordPress插件解决,优化速度的插件都是有一些可以用的,比如 WP Fastest Cache 也有自带的HTML压缩,或者用 LeSEO插件也有开启压缩。

看到如上图压缩网站HTML即可,功能效果是一样的。


评论