wordpress免插件优化压缩html代码

压缩HTML代码,其实就是减小网页源代码的大小,在这里记录一下,原理就是把源码中多余的空格和回车去掉,以此来减少源代码的体积,下面直接上代码,下面的代码放到主题的function.php文件里

//压缩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');

注意:如果发现部分JS代码压缩之前有错误或者特效有问题那么我们要把这部分的代码排除压缩

<!--wp-compress-html--><!--wp-compress-html no compression-->
不被压缩的部分
<!--wp-compress-html no compression--><!--wp-compress-html-->

文章代码不压缩

如果你的文章中有代码,你会发现它们都被压缩成一团了……这可不是我们想要的效果,所以添加下面代码避免这种情况的出现。

//当检测到文章内容中有代码标签时,文章内容不会被压缩
function unCompress($content) {
    if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) {
        $content = '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;
        $content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
    }
    return $content;
}
add_filter( "the_content", "unCompress");