WordPress自动添加标签内链代码(利于内页SEO优化)

 

最近想要做点内页的SEO优化了,觉得可以添加点内链了。而Wordpress标签转内链最方便了,网上的代码也非常多。所以这里就记录一下了。简单说下功能:一般就是检索站内所有的标签,然后设置一篇文章中同一个标签少于几次不自动链接,一篇文章中同一个标签最多自动链接几次。功能比较简单,但是非常实用。

WordPress自动添加标签内链代码

/* 4563博客 —— https://4563.org 自动为文章内的标签添加内链开始 */
$match_num_from = 1; //一篇文章中同一个标签少于几次不自动链接
$match_num_to = 3; //一篇文章中同一个标签最多自动链接几次
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, '$'),__('【查看含有[%s]标签的文章】'))."\"";
$url .= ' target="_blank"';
$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;
}
add_filter('the_content','tag_link',1);
/* 自动为文章内的标签添加内链结束 */

注意事项:

把上面代码添加到functions.php文件后,当我们发布、更新、保存文章时,会自动检测文章中是否有标签关键词,如果有就会自动添加这些标签的链接。虽然是自动的,但我们还需注意以下两点:

1、上面代码中$match_num_to = 1; //一篇文章中同一个标签最多自动链接几次,这个建议最多只设置3次。

2、代码中的$posttags = get_tags();表示自动为文章添加全站所有标签链接,我们还可以改成只为此文章设置的标签添加链接,只需将“$posttags = get_tags();”改成“$posttags = get_the_tags();”即可。

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论