在以往的 wordpress 優化教程中,我給大家推薦了 2 款代碼壓縮插件,今天主要是分享插件的代碼版本,也就是不使用插件,直接將代碼丟在 functions.php 中就可以使插件生效,好吧,又消滅一個插件!
- /*
- *壓縮 html 代碼
- * http://www.wpmee.com/wp-compress-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');
為什麼不使用插件,以及為什麼要使用插件呢?不使用插件,使用插件主要是方便移植!好了,今天的教程就到這裏,快去試一試吧。友情提示:如果想要在網頁源文件末尾查看壓縮信息,請刪除文中的註釋!
- <!--wp-compress-html--><!--wp-compress-html no compression-->
- 不被壓縮的部分
- <!--wp-compress-html no compression--><!--wp-compress-html-->