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

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

概述我们在写WordPress博客文章时经常会使用到站外链接,相信很多新手朋友也不会在意这里站外链接,但长期以往下来会造成你站点权重流失。可能有的人会说那不用

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。内存溢出小编现在分享给大家,也给大家做个参考。

我们在写 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;

}

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的纯代码WordPress站外链接自动添加nofollow和新窗口打开全部内容,希望文章能够帮你解决纯代码WordPress站外链接自动添加nofollow和新窗口打开所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zz/1007793.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存