WordPress程序在使用初期如果我们不用缓存插件或者其他方式提高加载速度也没有多大问题。不过,当我们的网站数据在增加,那势必会使得网站的速度很慢,这也是很多网友在使用WordPress吐槽的原因。如果说有一招能解决所有的优化速度问题,那也是不显示的。

比如优化WordPress网站速度有很多办法,比如在这篇文章中,我们可以进行压缩网站前端代码,这样减少网站的体积来提高打开速度。

//压缩前端html代码 https://www.itbulu.com/wp-compress-method.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');


我们只需要将代码添加到 Functions.php文件中然后我们刷新一下缓存看看,前端的代码是不是被压缩。


扫描二维码,在手机上阅读!