在以往的 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-->