PHP
//压缩html代码
function wp_compress_html(){
function wp_compress_html_main ($buffer){
$initial=strlen($buffer);
$buffer=explode("", $buffer);
$count=count ($buffer);
for ($i = 0; $i <= $count; $i++){
if (stristr($buffer[$i], '')) {
$buffer[$i]=(str_replace("", " ", $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";
return $buffer_out;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//压缩html代码
functionwp_compress_html(){
functionwp_compress_html_main($buffer){
$initial=strlen($buffer);
$buffer=explode("",$buffer);
$count=count($buffer);
for($i=0;$i<=$count;$i++){
if(stristr($buffer[$i],'')){
$buffer[$i]=(str_replace(""," ",$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";
return$buffer_out;
}
ob_start("wp_compress_html_main");
}
add_action('get_header','wp_compress_html');
部署方法:将以上代码粘贴到 WordPress 主题目录下的 functions.php 文件的最后一个 ?> 之前即可。
Ps:使用知更鸟主题的博客,需要将以上代码稍微改动一下,否则首页不会被压缩,已亲测!
修改方法:
将上述代码中的最后三行:
PHP
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');
1
2
3
ob_start("wp_compress_html_main");
}
add_action('get_header','wp_compress_html');
修改为:
PHP
if ( !is_admin() ) {
ob_start("wp_compress_html_main");
}
}
add_action('init', 'wp_compress_html');
1
2
3
4
5
if(!is_admin()){
ob_start("wp_compress_html_main");
}
}
add_action('init','wp_compress_html');
也就是将 get_header 动作修改为全局 init,然后再加上排除 WP 后台的判断,否则后台写文章就惨不忍睹了...(这样修改后,压缩生效的范围更大,若不出错,建议用修改后的代码!)
绕过压缩注释
PHP
此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误
1
2
3
此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误
只有这样包裹代码,被包裹的代码才不会被压缩,网上分享的大部分方法都是无效的。
顺带再说一个技巧,如果博客使用了 Crayon Syntax Highlighter 高亮插件,那么启用代码压缩之后,你会发现在文章页面双击代码切换到纯文本模式时,会发现代码全挤在一团了!好吧,全都给压缩了。
解决办法:
PHP
function unCompress($content) {
if(preg_match_all('/(crayon-|)/i', $content, $matches)) {
$content = ''.$content;
$content.= '';
}
return $content;
}
add_filter( "the_content", "unCompress");
1
2
3
4
5
6
7
8
functionunCompress($content){
if(preg_match_all('/(crayon-|)/i',$content,$matches)){
$content=''.$content;
$content.='';
}
return$content;
}
add_filter("the_content","unCompress");