自动为WordPress文章外链添加nofollow并新窗口打开

某些时候我们处于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\" target=\"_blank\" rel=\"external nofollow\" ",$content);
}
}
return $content;
}
//文章外链nofollow结束

高级玩法

另外,可以配合go.php文件,实现外链本地化打开。
效果如:https://www.mingdan.top/go.php?url=https://www.yundun.com/
特殊版go.php文件:https://www.tiezi.yz/archives/1214.html
整合后的代码

//给文章外链添加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=\"/go.php?url=$val\" target=\"_blank\" rel=\"external nofollow\" ",$content);
}
}
return $content;
}
//文章外链nofollow结束
角落吧大部分资源收集于网络,只做学习和交流使用,版权归原作者所有。发布的内容若侵犯到您的权益,请联系站长删除 ,我们将及时处理。
角落吧 » 自动为WordPress文章外链添加nofollow并新窗口打开

发表评论