WordPress 网站外链纯代码自动添加nofollow和blank属性

2023-05-3009:17:45网站管理维护Comments1,001 views字数 1231阅读模式

nofollow 其实对于网站SEO来说是非常好的 可以防止蜘蛛跟踪抓取外链。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

蜘蛛抓取站外链的话会分散权重,蜘蛛也就会跑到别人家去了,所以nofollow的建设非常的重要,当然了安装启用 Nofollow for external link 插件解决。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

纯代码解决的方法,将下面的代码添加到当前主题的 functions.php 文件即可。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

functions.php 文件路径:/wp-content/themes/主题/functions.php。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

// 站外链接自动添加nofollow属性
add_filter( 'the_content', 'cn_nf_url_parse');

function cn_nf_url_parse( $content ) {

$regexp = "<a\s[^>]*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;

}

效果图如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

WordPress 网站外链纯代码自动添加nofollow和blank属性文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

 文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

自动给文章/页面的站外链接添加nofollow属性(rel=”nofollow”),并且在新窗口打开这些链接(即添加 target=”_blank”属性)。如果已经手动给链接添加了 rel=”dofollow”,就不会添加 rel=”nofollow”;如果手动添加了 target=”_blank”,就不会重复添加。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/wg/43412.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/wg/43412.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定