之前一直使用WP keyword link这个插件给文章中的关键字增加内链,以优化SEO。但插件多了对博客的速度肯定有影响,所以找了个无插件实现的方法。实现起来也很简单,只需在主题文件夹中的function.php最后一个?>之前增加以下代码即可实现tag自动内链:
//tag自动内链$match_num_from = 1; //一篇文章中同一个关键字少于多少不锚文本(这个直接填1就好了)
$match_num_to = 2; //一篇文章中同一个关键字最多出现多少次锚文本(建议不超过2次)
//连接到WordPress的模块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 title="\"".str_replace('%s',addcslashes($cleankeyword," href="\"$link\"" target="_blank">".addcslashes($cleankeyword, '$')."</a>";
$limit = rand($match_num_from,$match_num_to);//不连接的代码$content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(]*>)|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 . ')(?!(([^<>]*?)>)|([^>]*?))\'s' . $case;$content = preg_replace($regEx,$url,$content,$limit);$content = str_replace( '%&&&&& %', stripslashes($ex_word), $content);}}return $content;}
更新你的博客看看,是不是已经有效果啦?





