免插件实现WordPress外部链接加上external nofollow(可设置白名单)

免插件实现默认给外部链接加上rel属性并加上external nofollow值(了解这个属性请google),找到风格模版目录下的functions.php文件,在最后加上如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
//外部链接直接加rel="nofollow"

function external_nofollow($content){
 preg_match_all('|href="(.*?)"|',$content,$matches);
 if($matches){
 foreach($matches[1] as $val){
 if( strpos($val,home_url())===false && (strpos($val,'http') || strpos($val,'.')) ) $content=str_replace("href="$val"", "href="$val" rel="external nofollow" ",$content);
 }
 }
 return $content;
}
add_filter('the_content','external_nofollow',999);

需要注意的一点是,大家搜索资料的时候可能更多说的是rel的nofollow。这里加的rel的值是external nofollow,这个只是比nofollow更标准一些而已,没有什么特殊的。

如果你有两个站,而不想给自己的网站加nofollow,假设有两个,wordpress.pianpai.com和pianpai.com两个不同域名的网站,那么可以修改上面的相关代码如下:

1
if( strpos($val,home_url())===false && (strpos($val,'http') || strpos($val,'.')) && strpos($val,'wordpress.pianpai.com') === false && strpos($val,'pianpai.com') === false )

结束。

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this post. TrackBack URL