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.
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
Thank you so much it works perfect.
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.
Muito bom.
You just saved me from installing another plugin. Thanks!
Thank you very much! I have successfully added the code into my site and it works just great!
Nice glad to hear it, enjoy the wordpress snippets!
[…] Source: WPsnipp […]