WordPress hack: Automatic “Nofollow” for external links in post content

October 22, 2012 at 4:12 pm

By default, WordPress does not automatically add a rel=”nofollow” attribute to external links within post content. If you want to do it, here is a simple hack to force WordPress to add the rel=”nofollow” attribute to every external link.

Paste the following code snippet in your functions.php file. Once you saved the file, all external links in your post content will be changed to nofollow.

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

Thanks to One Extra Pixel for the hack!

Tags: