WordPress Add NOFOLLOW To All External Links

This code snippet will add nofollow to all external links on your site.

Adding nofollow has advantages and disadvantages.

Advantages

  • Boost Domain Authority & PA Authority
  • Improve Relationship with Blogger
  • Improve Website Branding & Authority
  • Maintain Link Building Balance
  • Improve Website Traffic

Disadvantages

  • Less amount of comments even for great stuff !
  • Some Bloggers will not share there opinion even if they want to, because of nofollow attribute.

All code snippets are open source and everyone is free to use.

Example Code

Code should be placed in:

1
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 *  NOFOLLOW EXTERNAL LINKS
 *************************************************************/

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;
}

Check out more of our PHP snippets Click Here