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