在以往的 wordpress 最佳化教程中,我給大家推薦了 2 款程式碼壓縮外掛,今天主要是分享外掛的程式碼版本,也就是不使用外掛,直接將程式碼丟在 functions.php 中就可以使外掛生效,好吧,又消滅一個外掛!

  1. /*
  2. *壓縮 html 程式碼
  3. * http://www.wpmee.com/wp-compress-html ‎
  4. */
  5. function wp_compress_html()
  6. {
  7. function wp_compress_html_main ($buffer)
  8. {
  9.     $initial=strlen($buffer);
  10.     $buffer=explode("<!--wp-compress-html-->"$buffer);
  11.     $count=count ($buffer);
  12.     for ($i = 0; $i <= $count$i++)
  13.     {
  14.         if (stristr($buffer
    [$i], '<!--wp-compress-html no compression-->'))
  15.         {
  16.             $buffer[$i]=(str_replace("<!--wp-compress-html no compression-->"" "$buffer[$i]));
  17.         }
  18.         else
  19.         {
  20.             $buffer[$i]=(str_replace("\t"" "$buffer[$i]));
  21.             $buffer[$i]=(str_replace("\n\n""\n"$buffer[$i]));
  22.             $buffer[$i]=(str_replace("\n"""$buffer[$i]));
  23.             $buffer[$i]=(str_replace("\r"""$buffer[$i]));
  24.             while (stristr($buffer[$i], '  '))
  25.             {
  26.             $buffer[$i]=(str_replace("  "" "$buffer[$i]));
  27.             }
  28.         }
  29.         $buffer_out.=$buffer[$i];
  30.     }
  31.     //$final=strlen($buffer_out);
  32.     //$savings=($initial-$final)/$initial*100;
  33.     //$savings=round($savings, 2);
  34.     //$buffer_out.="\n<!--壓縮前的大小: $initial bytes; 壓縮後的大小: $final bytes; 節約:$savings% -->";
  35.     return $buffer_out;
  36. }
  37. ob_start("wp_compress_html_main");
  38. }
  39. add_action('get_header', 'wp_compress_html');

為什麼不使用外掛,以及為什麼要使用外掛呢?不使用外掛,使用外掛主要是方便移植!好了,今天的教程就到這裡,快去試一試吧。友情提示:如果想要在網頁原始檔末尾檢視壓縮資訊,請刪除文中的註釋!

  1. <!--wp-compress-html--><!--wp-compress-html no compression-->
  2. 不被壓縮的部分
  3. <!--wp-compress-html no compression--><!--wp-compress-html-->