How to Nofollow links within posts without plugin: WordPress

Okay, this is a quick tip to all those who’re protective about their Google Page Rank and skeptic about linking to other websites.

In order to “preserve” Google PageRank juice and not let it leak to websites you’re linking to (which is not confirmed from Google, but still), the only way is to add nofollow links to all your external links.

You can get this done easily using a plugin like  – External Nofollow.

But if you don’t like the idea of plugin and would like to have more control over how the nofollow attribute works (and saving some server load too of course), you can do it with a small bit of code.

add_filter('the_content', 'my_nofollow');

function my_nofollow($content) {
    //return stripslashes(wp_rel_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;
}

Adding the above piece of code to your functions.php will add the nofollow link attribute to all external links while excluding all internal links. Try it out.

Source: Deluxe Blog Tips

Comments are closed.