WordPress: Automatically Add "Nofollow" to External Links in Posts

WordPress: Automatically Add “Nofollow” to External Links in Posts

Do you often share links to websites that you do not want to be connected to by search engines? There might be multiple reasons to avoid being seen as recommending the site or passing link juice to it. You might be linking to sites to alert your readers about scams. You might want to do this for search engine optimization (SEO) purpose.

Wouldn’t it be nice if all your links in blog posts were automatically converted into “nofollow” links?

WordPress: Automatically Add "Nofollow" to External Links in Posts

WordPress automatically adds a rel=”nofollow” attribute to external links in comments, but it doesn’t happen automatically within post content. If you want to automatically add rel=”nofollow” attribute to external links in your post content without using any plug-in, here is a simple WordPress hack.

Paste the following code snippet in your WordPress theme’s functions.php file. Once you saved the file, all external links in your post content will be changed to nofollow. Please note that the code does not change the actual content but just alters it while displaying it on your blog/website. So, removing the snippet from the functions.php will revert the links to their original state.

add_filter('the_content', 'auto_nofollow');

function auto_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));

    return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}

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

Source: One Extra Pixel