为了优化网站的访问速度,对网页进行压缩是非常不错的一条方法。压缩页面减少了页面的体积提升了访问速度。

部署功能代码
//压缩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("nn", "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');
部署方法:将以上代码粘贴到WordPress主题目录下的functions.php文件的最后一个 ?> 之前即可。
Ps:使用知更鸟主题的博客,需要将以上代码稍微改动一下,否则首页不会被压缩。
修改方法:
将上述代码中的最后三行:
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');
修改为:
if ( !is_admin() ) {
ob_start("wp_compress_html_main");
}
}
add_action('init', 'wp_compress_html');
目前此代码在知更鸟主题Begin主题测试成功
插件方法
后台搜索WP-HTML-Compression即可,不建议用,太多插件会拖慢WP运行速度
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)