压缩代码一般是网站优化加速之必不可少的一步,很多朋友喜欢用一些Gzip的插件来压缩,其实完全没有必要的,下面介绍一种简单的代码形式压缩HTML代码。
在主题文件夹下的functions.php中加以下代码
- //压缩WordPress前端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("nn", "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;
- }
- //WordPress后台不压缩
- if ( !is_admin() ) {
- ob_start("wp_compress_html_main");
- }
- }
- add_action('init', '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");
脚下留心:
1、当我们的WordPress站点有某些页面或功能出现问题的时候,我们可以按照以下格式来添加标签以避免某些代码被压缩而出错。
此处代码不会被压缩,主要是避免压缩带来的错误,比如JS错误
2、本文这个功能只是压缩WordPress站点前端的HTML代码,如果想要压缩CSS代码的话,个人建议人工压缩,也就是通过复制主题的style.css文件中的CSS代码到一些压缩代码的在线工具中,比如这个,通过美化或压缩,然后再复制粘贴回style.css文件即可。