WordPress 为站外链接自动添加 nofollow 纯代码实现教程

wordpress 为站外链接自动添加 nofollow 纯代码实现教程,很多朋友都想要把站内的外链给去掉,如果是手动加 nofollow 标签很麻烦,所以今天119下载站就给大家分享一个自动加 nofollow 的方法,一起来看看吧。

方法一:

自动给页面的站外链接添加nofollow属性和新窗口打开

我们只需在主题的functions.php文件添加下面代码即可,DUX主题在主题目录下修改“functions-theme.php”文件即可。

/* 自动给页面的站外链接添加nofollow属性和新窗口打开 www.119xiazai.com 开始*/
add_filter( 'the_content', 'cn_nf_url_parse');
 
function cn_nf_url_parse( $content ) {
 
	$regexp = "<as[^>]*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 = '/targets*=s*"s*_blanks*"/';
				preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
				if( count($match) < 1 )
					$noFollow .= ' target="_blank" ';
 
				$pattern = '/rels*=s*"s*[n|d]ofollows*"/';
				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;
 
}
/* 自动给页面的站外链接添加nofollow属性和新窗口打开 www.119xiazai.com 结束*/

方法二:

在functions.php文件添加下面代码即可,DUX主题在主题目录下修改“functions-theme.php”文件即可。

自动给WordPress文章或评论内容的站外链接添加Nofollow属性,如果只想给评论内容的站外链接添加Nofollow属性,就把文章内容那段代码删除掉即可

/* 自动给WordPress文章或评论内容的站外链接添加Nofollow属性 www.119xiazai.com 开始*/

add_filter('the_content', 'auto_nofollow'); //nofollow文章内容的站外链接
 
add_filter('comment_text', 'auto_nofollow'); //nofollow评论内容的站外链接
 
function auto_nofollow($content) {
 //return stripslashes(wp_rel_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;
}
/* 自动给WordPress文章或评论内容的站外链接添加Nofollow属性 www.119xiazai.com 结束*/

添加后效果如下:

以上就是119下载站分享的“WordPress 为站外链接自动添加 nofollow 纯代码实现教程”的全部内容了,外链加 nofollow 标签是有利于SEO的,如果大家有什么不懂,可以在底下留言哦。

赞(0)
如有侵权请联系我,未经允许不得转载:119下载站 » WordPress 为站外链接自动添加 nofollow 纯代码实现教程

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址