WordPress纯代码为站外链接自动添加nofollow属性和新窗口打开

来自:网络
时间:2018-09-01
阅读:

我们在写WordPress博客文章时经常会使用到站外链接,相信很多新手朋友也不会在意这里站外链接,但长期以往下来会造成你站点权重流失。可能有的人会说那不用外链不行呀,那因为站外链接造成权重流失这种情况怎么办呢?如何解决呢?

其实方法很简单,我们只需把外链加上“nofollow”属性即可,其实目前很多主题本身应该自带这个功能。如果不知道自己的文章中的站外链接是否加有“rel=”nofollow”,请打开一个有站外链接的页面,右键查看源码,然后看外链后面是否添加了“rel=”nofollow”,如果有证明你站点的外链已做过nofollow处理,不会造成权重流失。如果没有,蜗牛将在这里为大家分享一个如何防止自己的WordPress博客因站外链接造成权重流失,依旧是纯代码实现WordPress文章的站外链接自动添加nofollow属性和在新窗口打开。

1、方法一。我们只需在主题的functions.php文件添加下面代码即可,DUX主题修改“functions-theme.php”文件,添加代码后会自动给你文章的的外链添加rel=”nofollow”、target=”_blank”属性,当然如果你有些链接已经手动添加,不会受到任何影响,代码也不会重复添加。

/* 自动给页面的站外链接添加nofollow属性和新窗口打开 蜗牛789 www.wn789.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属性和新窗口打开 蜗牛789 www.wn789.com 结束*/

2、方法二。下面代码是自动给WordPress文章或评论内容的站外链接添加Nofollow属性,如果只想给评论内容的站外链接添加Nofollow属性,就把文章内容那段代码删除掉即可。代码添加文章同样是主题的functions.php内。

/* 自动给WordPress文章或评论内容的站外链接添加Nofollow属性 蜗牛789 www.wn789.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属性 蜗牛789 www.wn789.com 结束*/

3、添加后效果如下:

返回顶部
顶部