前言:
有些时候我们网站引用外部网站导入链接的时候会可能流失自身的权重,所以我们习惯的做法就是 将外部的链接地址用nofollow标签属性标识出来。不管在行业中到底这样的做法有没有用,菜鸟站长之家还是将可以实现的方法记录下来,如果有需要的网友可以参考使用。
这里整理两个方法可以实现WordPress连接站外网站URL的时候自动添加nofollow,这样节省每次都需要手动添加的麻烦,提高效率。
第一、方法之一
/* 自动将站外链接加上nofollow标签 www.itbulu.com*/ add_filter('the_content', 'auto_nofollow'); function auto_nofollow($content) { return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content); } function auto_nofollow_callback($matches) { $link = $matches[0]; $site_link = get_bloginfo('url'); if (strpos($link, 'rel') === false) { $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link); } elseif (preg_match("%href=S(?!$site_link)%i", $link)) { $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link); } return $link; }
第二、方法之二
/* 自动将站外链接加上nofollow标签 www.itbulu.com*/ add_filter( 'the_content', 'cn_nf_url_parse'); function cn_nf_url_parse( $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; }
如果我们需要应用到网站中,选择其一的方法将代码添加到当前主题Functions.php文件中。就可以实现WordPress网站内容外部连接自动添加nofollow标签。
发表评论