DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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

11 Comments

  1. Thanks for the hack. Here is a plugin for people that don’t want to edit functions.php http://wordpress.org/extend/plugins/wp-links/

  2. Nice tweak buddy. I guess after adding this snippet, we will need to add re=”dofollow” within the link to give away dofollow links. Isn’t it?

  3. And this is what for I am waiting since a long time. Thanks a lot

  4. Great. I can get rid of plugin now and save tons of space and loading time

  5. Great tip, thanks!

  6. Great work. No need to search for the href tag and add rel=nofollow. Reduced my work, a smart trick.

  7. Thanks a lot for the hack. I really need this as I don’t want to waste my server resources with too many plugins.

  8. Thanks for the code snippet. It helps to get rid of a plugin I’m using now. How about doing the same for comment area also?

  9. A nice trick that works well. My only concern is that running a regular expression on every page load could be CPU expensive. Could be worth exploring a process that applies the same REGEX upon save instead.

  10. The problem with my blog is that links are not getting “nofollow”ed even though I use rel=”nofollow” tag. Example: I use the rel=”nofollow” but it doesn’t get displayed in the page source for a particular link. I put up this problem on the support forum. I was told that it might be due to a str_replace missing. My problem wasn’t clarified. Please help me regarding this.

  11. Nice Work …I really wanted this tweak

Leave a Comment

Your email address will not be published. Required fields are marked *