当然,在functions.php加入如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//压缩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'); |
注意,可能有些特效类的html压缩后会失效,所以要在前端去不想压缩的部分进行解析屏蔽。
1 2 3 |
<!--wp-compress-html--><!--wp-compress-html no compression--> 不被压缩的部分 <!--wp-compress-html no compression--><!--wp-compress-html--> |
有些人喜欢安装插件,但插件也常与其它插件不兼容。所以觉得能用代码搞定的最好