本文最后更新于:
WordPress网站做SEO优化时,内链是一个很重要的因素,而我们平时都是手动为文章添加内链,这样会牺牲一些时间,其实我们可以让网站自动为文章生成标签,并且为标签自动添加内链。以前有一款插件 WP Keyword Link ,但是刚才没搜索到,其实我们还可以使用纯代码实现这个功能
1、WordPress文章自动添加标签的代码
add_action('save_post', 'auto_add_tags');
function auto_add_tags()
{
$tags = get_tags(array('hide_empty' => false));
$post_id = get_the_ID();
$post_content = get_post($post_id)->post_content;
if ($tags) {
foreach ($tags as $tag) {
// 如果文章内容出现了已使用过的标签,自动添加这些标签
if (strpos($post_content, $tag->name) !== false) {
wp_set_post_tags($post_id, $tag->name, true);
}
}
}
}
2、WordPress自动为标签添加内链的代码:
//WordPress文章关键词自动内链
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){
$match_num_from = 1; //一个标签少于几次不链接
$match_num_to = 1; //一个标签最多链接几次
$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[^>]+>)(.*)<pre.*?>('.$ex_word.')(.*)<\/pre>(</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);
3、使用方法:添加到子比目录下functions.php文件里面
© 版权声明
THE END















![[子比主题美化]龙年移动端底部导航栏自定义icon-蛙言网](https://vip.helloimg.com/images/2023/12/30/oD9ayA.png)





![[子比主题美化]暂无评论内容位置图片美化-蛙言网](https://b66b.cn/wp-content/uploads/2023/12/20231224202631814-image.png)






![[免受权]Zibll子比主题 抽奖插件+任务系统+签到翻牌奖励-蛙言网](https://b66b.cn/wp-content/uploads/2025/11/20251113001301665-6_副本.webp)



![[子比主题美化]LV等级&VIP会员图标分享-蛙言网](https://vip.helloimg.com/images/2023/11/27/o0cUjh.png)














Felix 3月14日 22:270
好东西,学习一下!iqusc 3月11日 20:130
谢谢你的分享,我在蛙言网学到了很多!iqusc 3月11日 13:380
谢谢你的分享,我在蛙言网学到了很多!2761229739qq 3月11日 05:170
我今天会很忙,忙着夸夸你h5362202 3月9日 21:530
好东西,学习一下!h5362202 3月9日 21:450
好东西,学习一下!Felix 3月7日 01:440
蛙言网的教程很好用,谢谢!456464645d 3月6日 02:060
谢谢你的分享,我在蛙言网学到了很多!