How to Add Nofollow Attribute to External Links in WordPress Posts

wordpress nofollowexternal linksfunctions.phpseo best practicesnofollow attribute
Published·Modified·

To automatically add the external nofollow attribute to external links in your WordPress posts, simply add the following code to your theme's functions.php file. This code targets only external links and will not alter the attributes of internal site links.

// Automatically add nofollow attribute to external links in posts
add_filter('the_content','web589_the_content_nofollow',999);
function web589_the_content_nofollow($content){
 preg_match_all('/href="(.*?)"/',$content,$matches);
 if($matches){
  foreach($matches[1] as $val){
   if( strpos($val,home_url())===false ) $content=str_replace("href=\"$val\"", 

"href=\"$val\" rel=\"external nofollow\" ",$content);
  }
 }
 return $content;
}

Original source: Add Nofollow Attribute to External Links in WordPress Posts. All rights reserved by the original author. If there is any infringement, please contact QQ: 337003006 for deletion.