有些时候我们网站引用外部网站导入链接的时候会可能流失自身的权重,所以我们习惯的做法就是 将外部的链接地址用nofollow标签属性标识出来。不管在行业中到底这样的做法有没有用,老蒋还是将可以实现的方法记录下来,如果有需要的网友可以参考使用。

这里整理两个方法可以实现WordPress连接站外网站URL的时候自动添加nofollow,这样节省每次都需要手动添加的麻烦,提高效率。
第一、方法之一


/ 自动将站外链接加上nofollow标签 www.itbulu.com/
add_filter('the_content', 'auto_nofollow');
function auto_nofollow($content) {<br> return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}
function auto_nofollow_callback($matches) {<br> $link = $matches[0];<br> $site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {<br> $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);<br> } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {<br> $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);<br> }<br> return $link;
}

第二、方法之二

/ 自动将站外链接加上nofollow标签 www.itbulu.com/
add_filter( 'the_content', 'cn_nf_url_parse');
function cn_nf_url_parse( $content ) {<br> $regexp = "]href=(\"??)(1?)\12*>";
if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {<br> if( !empty($matches) ) {
$srcUrl = get_option('siteurl');<br> for ($i=0; $i < count($matches); $i++) {
$tag = $matches$i][0];<br> $tag2 = $matches[$i;
$url = $matches[$i][0];<br> $noFollow = '';
$pattern = '/target\s*=\s*"\s*_blank\s*"/';<br> preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
if( count($match) < 1 )<br> $noFollow .= ' target="_blank" ';
$pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';<br> 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;
}

如果我们需要应用到网站中,选择其一的方法将代码添加到当前主题Functions.php文件中。就可以实现WordPress网站内容外部连接自动添加nofollow标签。


  1. \" >
  2. >

扫描二维码,在手机上阅读!