前面大头有一篇文章有说明过给非本站链接加上nofollow属性可以防止权重流失,所以请务必给文章外部链接加上nofollow属性,但是手动添加属性有点太麻烦,下面大头分享一个让WordPress文章链接自动添加nofollow属性的方法。
下面这段代码不但可以给文章非本站链接自动加上nofollow属性,同时也可以给评论区的链接自动加上nofollow属性。
WordPress文章链接自动添加nofollow属性代码:
/**
* 自动给 WordPress 网站内容页导出链接添加nofollow属性和新窗口打开
* 教程参考白天博客。
*/
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {
$regexp = "]*href=(\"??)([^\" >]*?)\\1[^>]*>";
if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
if( !empty($matches) ) {
$srcUrl = get_option('siteurl');
for ($i=0; $i < count($matches); $i++)
{
$tag = $matches[$i][0];
$tag2 = $matches[$i][0];
$url = $matches[$i][0];
$noFollow = '';
$pattern = '/target\s*=\s*"\s*_blank\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )
$noFollow .= ' target="_blank" ';
$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 ) $noFollow .= ' rel="nofollow" '; $pos = strpos($url,$srcUrl); if ($pos === false) { $tag = rtrim ($tag,'>');
$tag .= $noFollow.'>';
$content = str_replace($tag2,$tag,$content);
}
}
}
}
$content = str_replace(']]>', ']]>', $content);
return $content;
}
将上面的代码复制添加到function.php文件里即可实现自动添加nofollow属性功能。