rel=”nofollow” for all external links in WordPress using code

Adding rel nofollow for external links on a webpage plays an important role. It tells search engines not to consider those links when search crawlers come to crawl your web page. So it will help you not to send your traffic juice to those external links.

There are lots of of WordPress plugin available which add rel=”nofollow” for all external links inside WordPress posts. But in this tutorial I am going to tell you how you can do it using your own code without using any plugin.

To do it you just need to add few lines of code inside your theme’s functions.php file that is given below:

// add nofollow to links
function nofollow_for_external($content) {
$content = preg_replace_callback(
function($m) {
if (strpos($m[1], "") === false)
return '<a href="'.$m[1].'" rel="nofollow">'.$m[2].'</a>';
return '<a href="'.$m[1].'">'.$m[2].'</a>';
return $content;
add_filter('the_content', 'nofollow_for_external');
// Stop self pingback
function disable_self_ping( &$links ) {
 $home = get_option( 'home' );
 foreach ( $links as $l => $link )
 if ( 0 === strpos( $link, $home ) )
add_action( 'pre_ping', 'disable_self_ping' );

Now change the “” into your own domain where your WordPress site is installed.

That’s all you need to do. Now go and test it. To test it if it working on your WordPress site or not, please open a post in your browser and check the external link in source code. To see the source code in chrome please right click on the page and click on “View page source”. You can see that all the external links of your WordPress site has rel=”nofollow tag.

You don’t need to add rel=”nofollow tag for external links from editor. It will be added automatically during the process of loading the post. So there is no hassle. You don’t need to do anything after adding these few lines of code in your theme’s functions.php.

Another thing you can do instead of adding this code in your theme’s functions.php, it is more better to create a separate plugin and then add this code inside the plugin’s file. Thus your code will not remove if you update your theme.

5 responses to “rel=”nofollow” for all external links in WordPress using code”

  1. WoomsSpopy says:

    Hi, this is off topic, but where did you get the html template for the web site? Thank you.

  2. anton says:

    this code works flawlessly, but what if want to add exceptions ? 2 or 3 external links will have follow atribute

  3. vahid says:

    How can I nofollow all external links by user role?

  4. Boaz says:

    The same question as Anton asked?
    How can we add exceptions for links with follow?

Leave a Reply

Your email address will not be published. Required fields are marked *