Quantcast
Channel: WPRecipes
Viewing all articles
Browse latest Browse all 121

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

$
0
0

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!


Viewing all articles
Browse latest Browse all 121

Trending Articles