精简代码可以减少网页加载的时间,增加蜘蛛爬取的效率,是SEO必备技能之一,下面小编就wordpress为例编写代码的精简。
将以下代码放到wordpress的functions.php中即可:
/*压缩html代码*/
function wp_compress_html()
{
function wp_compress_html_main ($buffer)
{
$initial=strlen($buffer);
$buffer=explode("", $buffer);
$count=count ($buffer);
for ($i = 0; $i <= $count; $i++)
{
if (stristr($buffer[$i], ''))
{
$buffer[$i]=(str_replace("", " ", $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";
return $buffer_out;
}
ob_start("wp_compress_html_main");
}
add_action('get_header', 'wp_compress_html');