WordPress文章/页面外链自动添加nofollow【代码/插件】
2025年3月3日 20:48
在 WordPress 的文章和页面中为外链自动添加 nofollow 属性是一个常见的 SEO 优化方法,可以防止将链接权重传递给外部网站。我们可以手动在主题的 functions.php 文件中添加相关代码来实现自动添加 nofollow,也可以使用插件。
一、主题文件添加代码
//文章与页面外链自动添加nofollow
function add_nofollow_to_external_links($content) {
$regexp = '/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>/i';
preg_match_all($regexp, $content, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (!strstr($match[2], home_url())) {
$content = str_replace($match[0], str_replace('<a ', '
}
}
return $content;
}
add_filter('the_content', 'add_nofollow_to_external_links');
Github代码:https://github.com/lingchenzi/blog/blob/main/wordpress/wordpress-nofollow
二、使用插件
1、Nofollow for External Link是一个更简单、专注于添加 nofollow 的插件;
2、WP External Links 是一个功能强大且广受欢迎的插件,不仅能为外链添加 nofollow,还提供额外的功能,例如让外链在新标签页中打开。