WordPress压缩html代码提升网页加载速度
对WordPress进行html代码压缩可以实现WordPress加速,此处保哥分享的是免Gzip插件来实现。压缩代码分为两部分,第一部分是压缩html代码,第二部分是解决代码压缩后导致html里的注释挤到一行,使很多代码失效,特别是部分js代码失效。
在当前主题模板下的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');
/**自动在存在高亮代码的文章收尾插入免压缩注释**/
function Code_Box($content) {
$matches = array();
/**以下是匹配高亮代码的关键词,本代码适用于 Crayon Syntax Highlighter 插件,其他插件请自行分析关键词即可**/
$c = "/(crayon-|<\/pre>)/i";
if(preg_match_all($c, $content, $matches) && is_single()) {
$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", "Code_Box" );
TAG
- WordPress自动重命名媒体库图片文件名
- WordPress禁止HTTP_USER_AGENT恶意采集与攻击
- WordPress删除文章时同步删除文章图片
- 添加扩展代码到WordPress核心文件functions.php更好的技巧
- WordPress判断用户邮箱地址来实现Gravatar头像本地化
- WordPress在每篇文章内容上方和下方添加指定内容的方法
- WordPress取消加载Google的dns-prefetch以及s.w.org
本文标题:《WordPress压缩html代码提升网页加载速度》
本文链接:https://zhangwenbao.com/wordpress-compression-html-code-to-improve-web-page-loading-speed.html
