这两天在给自己的网站做一些小小的 SEO 优化,比如增加一些内链。手动增加当然是太繁琐了,于是就想到了自动增加。下面就分享一下 WordPress 中自动为文章的标签添加内链的方法。
方法比较简单,在后台编辑主题的地方,找到 functions.php,然后在该文件最后添加上下面的代码即可:/**
* WordPress 自动为文章标签添加该标签的链接
* /auto-add-tag-link.html
*/
$match_num_from = 1; // 一个标签在文章中出现少于多少次不添加链接
$match_num_to = 1; // 一篇文章中同一个标签添加几次链接
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 = "
$url .= ' target="_blank"';
$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;
}
可以根据自己的需要修改文章标签的链接数。
亲自测试了,很好用。