WordPress程序确实是比较好用,但是如果我们不会提高网站的性能和优化代码资源会使得网站打开速度很慢,这也是有很多网友差评这个CMS的原因之一。总之,如果能玩转WP的用户已经算是在建站这一块有一定的造诣。我们要时刻的学习技术提升技能和技巧,包括我们看到有些网友查看源代码的时候代码都是压缩的,并不是我们正常的一行行显示的。
其中我们可以使用插件实现,这里老蒋分享一个直接用代码实现前端代码压缩的方法。
第一、代码部分
> //无插件压缩WordPress前端代码
> 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;
> }
> //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");
这里我们可以将代码添加到当前主题的Functions.php文件中。
第二、不压缩跳过
> <!--wp-compress-html--><!--wp-compress-html no compression-->
> 如果不希望被压缩的代码填写到这个里
> <!--wp-compress-html no compression--><!--wp-compress-html-->
如果我们不希望某段代码被压缩,这一用这个过滤掉。