Thursday, November 22, 2012

Automatic “Nofollow” for external links in post content of wordpress

Automatic “Nofollow” for external links in post content of wordpress

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

WordPress does not automatically by default add a rel=”nofollow” attribute to its external links within the post content. But If you want to add this attribute, the following solution help you to force WordPress to add the rel=”nofollow” attribute to every external link.

To make this work just Paste the following code in the functions.php file. Now save the file, you can see that 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;
}

No comments:

Post a Comment

I just got my #domain @BigRock. Get upto 25% off with my personalized coupon link Get upto 25% off