-
接触 WordPress 也有好几年的时间了,一只都是喜欢能用代码实现的东西,尽量不去使用插件!所以今天陈德馨想说说如何通过代码来压缩自己的前端页面。
至于我们为什么要压缩前端,这都是有理由的。
我们来举个例子。假设我现在手上有10斤重的杂物。现在通过压缩后,变得只有78斤重了,我提起来是不是会更加轻松?同理,压缩你的前端也是一样如此。所以我们有必要去压缩,虽然帮助可能不大,但是聊胜于无啊。
代码如下:(代码加在functions.php当中)
//压缩时绕过代码块 function unCompress($content) { if(preg_match_all('/(crayon-|<\/pre>)/i', $content, $matches)) { $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", "unCompress"); //压缩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');
纯代码实现WordPress 前台页面html压缩
1644人参与 |分类: 站长百科|时间: 2015年05月28日
来源:Z-Blog博客(微信:weixinhao),转载请保留出处和链接!
相关文章
- 2020-05-09WordPress使用timthumb.php截取文章缩略图
- 2020-01-10作为站长应该懂得的7大搜索引擎站长平台
- 2019-10-22个人博客网站用什么程序比较好?
- 2019-10-12头条搜索站长平台如何添加网站和sitemap文件?附图文教程
- 2019-09-26PHP环境下是选择Apache和Nginx?
- 2019-09-11网站运维人员必做的7项网站维护工作
- 2019-08-26现在还要必要坚持做PC网站或个人博客吗?
- 2019-08-03宝塔面板+云锁nginx自编译web防护的图文教程
- 2019-07-08解决国内主机服务器 WordPress 后台异常卡顿的问题
- 2019-07-02网站启用SSL自动301跳转到HTTPS教程
评论专区请在后台修改