Use the rel=”nofollow” attribute for all external links in WordPress by using code

External links from sites outside of your site will not be counted by search engines. So you can stop worrying about them when they come to index your content.

There are tons of WordPress plugins out there that automate the process of adding rel=”nofollow” to links inside WordPress posts, but you can do it using your own code without any plugins.

To do that, you need to add a few lines of code to your theme’s functions.php file, which 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="noopener noreferrer 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

Well done! You don’t need to do anything else; you can go and test it. To see if it’s working on your WordPress site, visit a post and check the external link in the source code. This is a problem that you can solve using the Chrome View page source. If you do this, you’ll see all the external links to your WordPress site and that they all have the rel=”nofollow” tag.

You don’t need to use this tag for every external link in the editor. WordPress automatically adds this tag when you load your post. So there is no need to do anything after adding these few line of code in your theme’s functions.php file.

You can also add this code to a specific plugin, so that your changes will persist even if the theme gets updated.


Leave a Comment