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

我们在写 wordpress 博客文章时经常会使用到站外链接,相信很多新手朋友也不会在意这里站外链接,但长期以往下来会造成你站点权重流失。可能有的人会说那不用外链不行呀,那因为站外链接造成权重流失这种情况怎么办呢?如何解决呢?其实方法很简单,我们只需把外链加上“nofollow”属性即可,其实目前很多主题本身应该自带这个功能。如果不知道自己的文章中的站外链接是否加有“rel=”nofollow”,请打开一个有站外链接的页面,右键查看源码,然后看外链后面是否添加了“rel=”nofollow”,如果有证明你站点的外链已做过 nofollow 处理,不会造成权重流失。如果没有,博主将在这里为大家分享一个如何防止自己的 WordPress 博客因站外链接造成权重流失,依旧是纯代码实现 WordPress 文章的站外链接自动添加 nofollow 属性和在新窗口打开。

方法一

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

    add_filter( 'the_content', 'cn_nf_url_parse');
    function cn_nf_url_parse( $content ) {
 
    	$regexp = "]*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;
 
    }

方法二

第一行代码是给文章内的外链自动添加 nofollow 标签,第三方代码是给评论内的外链自动添加 nofollow 标签,这两种情况,可自行选择。如果你仅仅需要的是给文章内的外链添加 nofollow 标签,那么请删除第三行代码即可。代码添加文章同样是主题的 functions.php 内。

    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('/]+/', '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;
    }

 

http://xzh.i3geek.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请不要用于商业用途及非法用途,否则后果自负!
3. 如果你也有好源码或者教程,可以到审核区发布,分享有金币奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"qq301.com",如遇到无法解压的请联系管理员!
资源客是一个优秀的分享资源站,本站资源均为各位友友分享而来,特殊原创会标明如有侵犯版权等可联系删除

资源客 » 纯代码WordPress站外链接自动添加nofollow和新窗口打开