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. Saranraj Gunasekaran March 4, 2022 at 3:08 am

    Hi Thanks for this but I need external links to open a new tab with No follow tag. Is there any code? I would be happy if you help me on this

  2. Saranraj Gunasekaran March 4, 2022 at 2:17 am

    Thank you so much it works perfect.

  3. This is good code, but it’s limited to matching exactly get_bloginfo(‘url’). What I’d like it to do is match my domain. That way http://www.site.com and billing.site.com and support.site.com are all whitelisted. The current code treats anything that’s not on the same sub-domain as the blog as an external site.

  4. Muito bom.

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

  6. 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!

  7. 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!