已经有一个很古老的插件可以实现了,就是“WP-HTML-Compression”。不过本篇要使用的是加入主函数的代码法:
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');
加入functions.php内,保存再刷新下前台页面,查看源代码,是否压缩过了?
压缩页面有可能会出一些问题,比如某些特效失效了,那么我们还需要对这些位置进行禁止压缩操作,方法是:
<!--wp-compress-html--><!--wp-compress-html no compression--> 不被压缩的部分 <!--wp-compress-html no compression--><!--wp-compress-html-->
将不想被压缩的部分前后加入这个白名单代码之内,那么这段代码就不会被压缩到!友情提醒,压缩后有可能会检测不到友情链接,这时候也是需要这个白名单代码来将友链的部分进行禁止压缩操作!

