No-follow All External Links In WordPress Without Plugin

With Google getting more and more concerned about quality, it has become very difficult to maintain your rank in search results. The first thing to rank higher in SERPs is to have good quality content on your website. One more thing Google takes into account while ranking web pages is the Page Rank, introduced by Google itself. But Page Rank is volatile, it passes on to the web pages that a page links to. And hence you must be very careful while linking to web pages outside your domain.

Page rank has one more quality, it is not passed to links that are no-followed, and that is why we have a code snippet that can automatically no-follow all the links to external websites.

add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');

function my_nofollow($content) {
    return preg_replace_callback('/]+/', '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;
}

This code no-follows all the external links from the_content and the_excerpt functions. Just place this code in the functions.php file of your active theme and it takes care of everything else. If you are a newbie and have never edited the functions.php file, then this guide can help.

Related Post