WordPress纯代码实现前端页面HTML完美压缩

 4656

前言:压缩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("\n\n", "\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. ob_start("wp_compress_html_main");
  28. }
  29. add_action('get_header', 'wp_compress_html');
  30. //当检测到文章内容中有代码标签时文章内容不会被压缩
  31. function unCompress($content) {
  32.     if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) {
  33.         $content = '<!--wp-compress-html--><!--wp-compress-html no compression-->'.$content;
  34.         $content.= '<!--wp-compress-html no compression--><!--wp-compress-html-->';
  35.     }
  36.     return $content;
  37. }
  38. add_filter( "the_content", "unCompress");


本文网址:https://www.zztuku.com/detail-7710.html
站长图库 - WordPress纯代码实现前端页面HTML完美压缩
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐