Add Automatic “Nofollow” tag to external links

WordPress is a great platform. Dofollow and Nofollow Tag are very easy to manage in WordPress. By default, It does not automatically add a rel=”nofollow” attribute to external links within post content. If you want to add rel=”nofollow” to post, every time you have to add manually it by text editors or install a plugin to do so But too many plugins can affect your site performance. So we suggest you always to use the less plugins for faster page load time.

You can add nofollow tag to post content and excerpts without any plugin.

How to add nofollow links in WordPress for external links Automatically

How to add nofollow automatically wordpress

Today we are going to show you how to add “Nofollow” tag to external links automatically without any plugin. Go to Appearance>>Editor and open function.php file. Copy and paste the following code in your theme funtion.php file.

</pre>
add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');

function my_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}

function my_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;
}
<pre>

The above code will add the ‘Nofollow’ tag to both the post content and excerpts. If you don’t want to add in excerpts just remove the line 2.

Pin It on Pinterest

Shares
Share This