Automatically Add Nofollow to External Links in WordPress Posts
Sometimes, for SEO considerations, we need to add the nofollow tag to external links in WordPress articles to tell search engines not to track these links. While we can add this tag manually, it becomes very troublesome and inefficient if an article contains many external links. Here is a method to automatically add the nofollow tag to external links in WordPress articles.
I searched online for code, but many were either incorrect or unusable. After persistent effort, I found the correct code, which has been tested and works perfectly. The method is very simple: just add the following code to the functions.php file in your theme directory:
// Add nofollow to external links in posts
add_filter('the_content', 'web589_the_content_nofollow', 999);
function web589_the_content_nofollow($content) {
preg_match_all('/href="(.*?)"/', $content, $matches);
if ($matches) {
foreach ($matches[1] as $val) {
if (strpos($val, home_url()) === false) {
$content = str_replace("href=\"$val\"", "href=\"$val\" rel=\"external nofollow\" ", $content);
}
}
}
return $content;
}
// End of external links nofollow
After applying this method, external links in your posts will automatically have the nofollow tag added, eliminating the need for manual operation. The advantage is speed and convenience; however, the disadvantage is that it is difficult to control. For example, if you do not want to add the nofollow tag to certain external links in a specific article, you will need to weigh the options.
Therefore, here is also a method for manually adding the nofollow tag:
Note: Do not use this method simultaneously with the code above.
<a href="URL" title="Title" rel="nofollow" target="_blank">Link Text</a>