WordPress不用插件,这样做轻松压缩网页代码

大话运营 768 0

首先我们要在functions.php文件中加入代码:

/* 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);   
    return $buffer_out;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');

然后我们刷新网页就 OK 了。那么如果我们要一些地方不要压缩,该如何做呢?

我们可以按照这个格式:

<!--wp-compress-html--><!--wp-compress-html no compression-->

不想压缩的地方

<!--wp-compress-html no compression--><!--wp-compress-html-->

如果你使用Prism.js实现代码高亮,不妨可以试试。


标签: wordpress建站教程

大话运营

发表评论 (已有0条评论)

还木有评论哦,快来抢沙发吧~