纯代码WordPress站外链接自动添加nofollow和新窗口打开
以下代码由PHP站长网 52php.cn收集自互联网现在PHP站长网小编把它分享给大家,仅供参考 我们在写 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 = '/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,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; } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |