尽管说压缩wordpress页面后对查看源代码来说不太友好,更可以说是惨目忍睹。但是压缩页面的好处就是减少了页面的体积,从访问速度上来说,更快些,尽管这些是肉眼看不到的,但是至少本人喜欢这样,另一方面就是给扒皮者制造麻烦,他们不得不重新整理页面代码的整洁性!
给wordpress页面进行压缩不是压缩自己的实际代码,而是对前台html页面代码的压缩!相关插件是“WP-HTML-Compression”。我们现在来讲一下不通过插件,使用纯代码来实现压缩wordpress前端html页面代码这个功能。
1.打开主题文件夹里的functions.php文件,将下面的代码贴入:
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 30 31 32 33 34 35 36 | //压缩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 ; } ob_start( "wp_compress_html_main" ); } add_action( 'get_header' , 'wp_compress_html' ); |
将代码贴入后,在刷新下前台页面,查看源代码,是否压缩过了?
压缩页面会衍生出一些问题,比如说,某些位置的某些特效失效了,那么我们还需要对某些位置进行禁止压缩操作,方法是:
1 2 3 | <!--wp-compress-html--><!--wp-compress-html no compression--> 不被压缩的部分 <!--wp-compress-html no compression--><!--wp-compress-html--> |
意思就是说将不想被压缩的部分前后加入这个屏蔽码,即可将这段代码不被压缩到!
2016年04月08日 10:15 沙发
非常好 非常棒哦~
2019年03月11日 18:12 板凳
将代码贴入后,在刷新下前台页面,查看源代码,是否压缩过了?