X

Nofollow External Links Only, the_content and the_excerpt

Snippets by IsItWP

Do you want to add rel=nofollow automatically to all the external links on your website? While there’s probably a plugin for this, we have created a quick code snippet that you can use to nofollow external links only in WordPress.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

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;
}

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly add code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 43 best photography themes for WordPress and how to create stunning WordPress optin forms.

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!