Nofollow external links only, the_content and the_excerpt

This great little snippet that will add rel="nofollow" to external links within both the_content and the_excerpt. Add this snippet to the functions.php of your wordpress theme to enable nofollow external links.

Code Snippet:

add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');

function my_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;

Comments  Leave a Reply

  1. Muito bom.

  2. You just saved me from installing another plugin. Thanks!

  3. Thank you very much! I have successfully added the code into my site and it works just great!

    1. Nice glad to hear it, enjoy the wordpress snippets!

  4. Aggiungi il Nofollow ai link esterni in the_content e the_excerpt | Wordpress Style June 23, 2011 at 8:21 am

    […] Source: WPsnipp […]

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!