从SEO细节角度考虑的话,我们对于网站中的外部跳转链接都是需要加上nofollow标签不给传递权重值的。有些时候我们手动加的话会忘记有的加上有的没加上,于是我们可以用自动的办法实现。我们可以不需要插件直接用代码可以将nofollow自动加入到我们内容中有外部连接的URL中。

//给文章外链添加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且新窗口打开
add_filter( 'the_content', 'auto_nofollow_for_external_link');
function auto_nofollow_for_external_link( $content ) {
$regexp = "<a\s[^>]*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;
}
我们根据需要选择,一般我们用第二种。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END