随着我们采用的WordPress程序建站推进,会越来越觉得网站的打开速度变慢,这个与我们实际选择的主机是有关系的,但是也与我们网站使用的主题、插件、网站中的图片,以及是否优化WordPress网站性能速度有关系。对于代码前端,我们可以使用压缩插件将代码都压缩起来,这样减少页面的体积。
对于插件有很多,我们可以选择使用WP HTML Compression插件,同时,我们也可以使用下面老蒋找到的无插件版本效果也是一样的。


function wp_compress_html(){
function wp_compress_html_main ($buffer){<br> $initial=strlen($buffer);<br> $buffer=explode("<!--wp-compress-html-->", $buffer);<br> $count=count ($buffer);<br> for ($i = 0; $i <= $count; $i++){<br> if (stristr($buffer[$i], '<!--wp-compress-html no compression-->')) {<br> $buffer[$i]=(str_replace("<!--wp-compress-html no compression-->", " ", $buffer[$i]));<br> } else {<br> $buffer[$i]=(str_replace("\t", " ", $buffer[$i]));<br> $buffer[$i]=(str_replace("\n\n", "\n", $buffer[$i]));<br> $buffer[$i]=(str_replace("\n", "", $buffer[$i]));<br> $buffer[$i]=(str_replace("\r", "", $buffer[$i]));<br> while (stristr($buffer[$i], ' ')) {<br> $buffer[$i]=(str_replace(" ", " ", $buffer[$i]));<br> }<br> }<br> $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');

将代码添加到当前主题的Functions.php页面中,我们就可以刷新缓存看看效果。


扫描二维码,在手机上阅读!