压缩wordpress前端html页面代码,加快访问速度

2016年4月8日 建站技术 浏览 4,309 2 条评论 A+

尽管说压缩wordpress页面后对查看源代码来说不太友好,更可以说是惨目忍睹。但是压缩页面的好处就是减少了页面的体积,从访问速度上来说,更快些,尽管这些是肉眼看不到的,但是至少本人喜欢这样,另一方面就是给扒皮者制造麻烦,他们不得不重新整理页面代码的整洁性!

压缩wordpress前端html页面代码,加快访问速度

给wordpress页面进行压缩不是压缩自己的实际代码,而是对前台html页面代码的压缩!相关插件是“WP-HTML-Compression”。我们现在来讲一下不通过插件,使用纯代码来实现压缩wordpress前端html页面代码这个功能。

1.打开主题文件夹里的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;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');

将代码贴入后,在刷新下前台页面,查看源代码,是否压缩过了?

压缩页面会衍生出一些问题,比如说,某些位置的某些特效失效了,那么我们还需要对某些位置进行禁止压缩操作,方法是:

<!--wp-compress-html--><!--wp-compress-html no compression-->
不被压缩的部分
<!--wp-compress-html no compression--><!--wp-compress-html-->

意思就是说将不想被压缩的部分前后加入这个屏蔽码,即可将这段代码不被压缩到!

目前评论:2   其中:访客  2   博主  0

  1. 博客导航点我收录你 2

    非常好 非常棒哦~

  2. 币安链 4

    将代码贴入后,在刷新下前台页面,查看源代码,是否压缩过了?

评论加载中...

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: