压缩代码一般是网站优化加速之必不可少的一步,很多朋友喜欢用一些Gzip的插件来压缩,其实完全没有必要的,下面介绍一种简单的代码形式压缩HTML代码。
在主题文件夹下的functions.php中加以下代码

  1. //压缩WordPress前端html代码 
  2. function wp_compress_html(){
  3.     function wp_compress_html_main ($buffer){
  4.         $initial=strlen($buffer);
  5.         $buffer=explode("<!--wp-compress-html-->"$buffer);
  6.         $count=count ($buffer);
  7.         for ($i = 0; $i <= $count$i++){
  8.             if (stristr($buffer[$i], '<!--wp-compress-html no compression-->')) {
  9.                 $buffer[$i]=(str_replace("<!--wp-compress-html no compression-->"" "$buffer[$i]));
  10.             } else {
  11.                 $buffer[$i]=(str_replace("t"" "$buffer[$i]));
  12.                 $buffer[$i]=(str_replace("nn""n"$buffer[$i]));
  13.                 $buffer[$i]=(str_replace("n"""$buffer[$i]));
  14.                 $buffer[$i]=(str_replace("r"""$buffer[$i]));
  15.                 while (stristr($buffer[$i], '  ')) {
  16.                     $buffer[$i]=(str_replace("  "" "$buffer[$i]));
  17.                 }
  18.             }
  19.             $buffer_out.=$buffer[$i];
  20.         }
  21.         $final=strlen($buffer_out);
  22.         $savings=($initial-$final)/$initial*100;
  23.         $savings=round($savings, 2);
  24.         $buffer_out.="n<!--压缩前的大小: $initial bytes; 压缩后的大小: $final bytes; 节约:$savings% -->";
  25.     return $buffer_out;
  26. }
  27. //WordPress后台不压缩
  28. if ( !is_admin() ) {
  29.         ob_start("wp_compress_html_main");
  30.     }
  31. }
  32. add_action('init', 'wp_compress_html');
  33. //当检测到文章内容中有代码标签时文章内容不会被压缩
  34. function unCompress($content) {
  35.     if(preg_match_all('/(crayon-|</pre>)/i', $content$matches)) {
  36.         $content = '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;
  37.         $content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
  38.     }
  39.     return $content;
  40. }
  41. add_filter( "the_content""unCompress");

脚下留心:
1、当我们的WordPress站点有某些页面或功能出现问题的时候,我们可以按照以下格式来添加标签以避免某些代码被压缩而出错。

此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误

2、本文这个功能只是压缩WordPress站点前端的HTML代码,如果想要压缩CSS代码的话,个人建议人工压缩,也就是通过复制主题的style.css文件中的CSS代码到一些压缩代码的在线工具中,比如这个,通过美化或压缩,然后再复制粘贴回style.css文件即可。

豫ICP备11029947号