某些时候我们处于 SEO 考虑需要对 WordPress 文章中的外链添加 nofollow 标签来告诉搜索引擎不要追踪此链接,我们可以手动添加这个标签,但是如果一篇文章外链较多的话会显得非常麻烦,也不利于提高工作效率。那么这里分享一个如何为 WordPress 文章的外链自动添加 nofollow 的方法,希望对大家有用。
在网上找了很多代码要么就是错误,要么就是不可用。不过通过最终的努力找到了正确的代码,亲测可用。方法非常的简单,只需要在你的主题目录下的 functions.php 中添加下面的代码即可:
//给文章外链添加 nofollow add_filter('the_content','web589_the_content_nofollow',999); function web589_the_content_nofollow($content){ preg_match_all('/href="(.*?)"/',$content,$matches); if($matches){ foreach($matches[1] as $val){ if( strpos($val,home_url())===false ) $content=str_replace("href="$val"", "href="$val" rel="external nofollow" ",$content); } } return $content; } //文章外链 nofollow 结束
通过这个方法后文章中的外链就会自动添加 nofollow 标签,而不用我们手动去操作,优点就是快速方便,缺点是不太好控制,比如某篇文章中某些外链你不想添加 nofollow 标签,那么久需要自己去权衡了。因此再附上一句手动添加 nofollow 的方法,注意:不可和上面代码同时使用。 (以前闲的没事手贱,就有的还加了个 nofollow,现在木法用了!!! 😥)
<a href = "URL" title = "标题" rel="nofollow" target = "_blank"> 链接文本</a>