描文本在网站的SEO优化中占据着很大的比重,合理的关键词描文本可以给网站的排名带来很大的帮助。大多数建站系统在布局文章关键的描文本时都要手动去更改、去更新。这样的工作量是非常庞大的,而且效率极其低下。而有些聪明的站长可能会利用执行数据库语言来批量的更换关键词的描文本。而wordpress作为最流行的建站系统,有很多实用的插件来弥补wordpress自身的不足。上次魔客吧曾介绍的WP keyword Link Plugin就是一款wordpress的自动描文本插件。今天魔客吧来介绍下如何使用非插件的方法来实现wordpress的自动描文本。
打开当前使用的wordpress主题的functions.php文件,并加入以下代码:
$match_num_from = 1;
//每篇文章中的关键词数量低于多少则不描文本(请不要低于1)$match_num_to = 1;
//同一篇文章中,同一个关键词最多描几次文本(这里是1次,建议不超过2次)add_filter('the_content','tag_link',1);
function tag_sort($a, $b){
if ( $a->name == $b->name ) return 0;
return ( strlen($a->name) > strlen($b->name) ) ? -1 : 1;
}
function tag_link($content){
global $match_num_from,$match_num_to;
$posttags = get_the_tags();
if ($posttags) {
usort($posttags, "tag_sort");
foreach($posttags as $tag) {
$link = get_tag_link($tag->term_id);
$keyword = $tag->name;
$cleankeyword = stripslashes($keyword);
$url = "".addcslashes($cleankeyword, '$')."";
$limit = rand($match_num_from,$match_num_to);
$content = preg_replace( '|(]+>)(.*)('.$ex_word.')(.*)(]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
$content = preg_replace( '|()|U'.$case, '$1$2%&&&&&%$4$5', $content);
$cleankeyword = preg_quote($cleankeyword,''');
$regEx = ''(?!((<.*?)|(]*?)>)|([^>]*?))'s' . $case;
$content = preg_replace($regEx,$url,$content,$limit);
$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
}
}
return $content;
}
PS:此段代码只会在已经存在的tag上面文本,如果需要自定义其他描文本请使用本文中提到的WP keyword Link Plugin插件。