将以下代码粘贴到 WordPress 主题目录下的 functions.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;
}
if ( !is_admin() ) {
ob_start("wp_compress_html_main");
}
}
add_action('init', 'wp_compress_html');
排除后台不压缩,只针对前台进行压缩,压缩生效的范围更大。
绕过压缩注释
<!--wp-compress-html--><!--wp-compress-html no compression-->
此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误
<!--wp-compress-html no compression--><!--wp-compress-html-->
只有这样包裹代码,被包裹的代码才不会被压缩,网上分享的大部分方法都是无效的。
一般可以把代码里的 script脚本 前后进行包括以免压缩后出错。
如果博客使用了 Crayon Syntax Highlighter 高亮插件,那么启用代码压缩之后,你会发现在文章页面双击代码切换到纯文本模式时,会发现代码全挤在一团了!好吧,全都给压缩了。
解决办法
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");
同理如果使用的是 pure highlightjs 高亮插件按下面方法修改即可
function unCompress($content) {
if(preg_match_all('/(pure-highlightjs|<\/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");
评论