WordPress文章链接自动添加nofollow属性并以新窗口打开,WordPress文章链接自动添加nofollow属性

Wordpress3年前 (2022)发布 SUYEONE
1.1K 0 0

WordPress的评论功能历来是双刃剑,它鼓励了用户与网站所有者之间的互动,但也存在一个问题:它可能被利用来创建外部链接,这可能导致权重流失和用户流失。为了解决这个问题,一个有效的策略是在这些外部链接上添加nofollow属性,防止搜索引擎追踪它们。同时,我们还可以让这些链接在新窗口中打开,以提供更好的用户体验。

以下是一种方法,可以在WordPress的内容页面中自动为外部链接添加nofollow属性并使其在新窗口中打开。首先,你需要将以下代码复制并粘贴到你的当前主题的function.php文件中:

“`
/**
* 自动为WordPress文章链接添加nofollow属性并新窗口打开
* 参考来源:https://zhujicankao.com/66490.html
*/
add_filter( ‘the_content’, ‘cn_nf_url_parse’);
function cn_nf_url_parse( $content ) {
$regex = ‘]*href=(\”??)([^\” >]*?)\\1[^>]*>’;
preg_match_all(“/$regex/siU”, $content, $matches, PREG_SET_ORDER);

if(!empty($matches)) {
$siteUrl = get_option(‘siteurl’);
foreach ($matches as $index => $link) {
$tag = $link[0];
$tag2 = $link[0];
$url = $link[0];
$nofollowAttr = ”;

// 检查是否已设置target=”_blank”
preg_match(‘/target\s*=\s*”\s*_blank\s*”/’, $tag2, $targetMatch, PREG_OFFSET_CAPTURE);
if (count($targetMatch) < 1) {
$nofollowAttr .= ' target="_blank" ';
}

// 检查是否已设置rel="nofollow"
preg_match('/rel\s*=\s*"\s*[n|d]ofollow\s*"/', $tag2, $relMatch, PREG_OFFSET_CAPTURE);
if (count($relMatch) ‘);
$modifiedTag .= $nofollowAttr . ‘>’;
$content = str_replace($tag2, $modifiedTag, $content);
}
}
}

// 修复]]>问题
$content = str_replace(‘]]>’, ‘]]>’, $content);

return $content;
}
“`

完成上述步骤后,你的WordPress网站内容页面上的外部链接将会自动添加nofollow属性,并在新窗口中打开,从而帮助你保护网站权重和用户流量。

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!