How to add nofollow to all External Links in your WordPress Blog

Simple tutorial which will help you add nofollow attribute to all external links in your WordPress Blog without using any plugins.It’s not  easy task for you to add nofollow attributes each time you hyperlink something in your posts.

What is Nofollow?

nofollow HTML attribute provides a way to webmasters for instructing search engines to “not follow the target links“As a result of this Google does not transfer Page Rank or anchor text across these links.

How to add nofollow to all External Links in your WordPress Blog

Code Snippet to add nofollow to all External Links :

At the first point I want to tell you one thing, there are lot of WordPress plugins available to achieve the target of adding nofollow attribute to Links on your blog.But remember one thing using plugins for each small task is not a good thing from security point of view as well as Performance point of view.

The Solution is to add the below lines of code into your WordPress themes functions.php file.Thanks to DeluxeBlogTips for sharing this valuable tip upfront.

add_filter(‘the_content’, ‘my_nofollow’);

function my_nofollow($content) {
//return stripslashes(wp_rel_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;
}

Caution: Please take a backup of the file functions.php before making any changes to it., so that it can be used to restore in case of any issues

Hope you like this tutorial, Please do share your views & let us know if you know any other better option to add nofollow to external links on WordPress without using any plugin so that it can be helpful for fellow readers.

  • shakil

    really very useful codes. Helped me a lot. Thanks friend

  • Ansh

    Thanks for the code..