WordPress SEO优化之tag关键词自动描文本

描文本在网站的seo优化中占据着很大的比重,合理的关键词描文本可以给网站的排名带来很大的帮助。大多数建站系统在布局文章关键的描文本时都要手动去更改、去更新。这样的工作量是非常庞大的,而且效率极其低下。而有些聪明的站长可能会利用执行数据库语言来批量的更换关键词的描文本。而WordPress作为最流行的建站系统,有很多实用的插件来弥补WordPress自身的不足。今天梦飞扬来介绍下如何使用非插件的方法来实现WordPress的自动描文本。

tag关键词自动描文本实现方法,将以下代码添加至当前主题的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 = "<a href="$link" title="".str_replace('%s',addcslashes($cleankeyword, '$'),__('View all posts in %s')).""";
 $url .= ' target="_blank" class="tag_link"';
 $url .= ">".addcslashes($cleankeyword, '$')."</a>";
 $limit = rand($match_num_from,$match_num_to);

 $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
 $content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);

 $cleankeyword = preg_quote($cleankeyword,''');

 $regEx = ''(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))'s' . $case;

 $content = preg_replace($regEx,$url,$content,$limit);

 $content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);

 }
 }
 return $content;
}

PS:此段代码只会在已经存在的tag上面文本,如果需要自定义其他描文本需使用WP keyword Link Plugin插件。

展开评论