Publish: 2014-11-02 | Modify: 2014-11-02
Sometimes, for SEO considerations, we need to add the nofollow
tag to external links in WordPress articles to tell search engines not to track these links. We can manually add this tag, but if an article has many external links, it can be very cumbersome and not conducive to improving work efficiency. Here, I will share a method on how to automatically add the nofollow
attribute to external links in WordPress articles, hoping it will be useful to everyone.
I have searched online for many codes, but either they are incorrect or not usable. However, after a final effort, I found the correct code, and it has been tested and proven to be effective. The method is very simple, just add the following code to the functions.php
file in your theme directory:
// Add nofollow to external links in the content
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;
}
// End of adding nofollow to external links in the content
After using this method, the external links in the article will automatically have the nofollow
attribute added, without the need for manual operation. The advantage is that it is fast and convenient. The disadvantage is that it is not easy to control. For example, if you don't want to add the nofollow
attribute to certain external links in an article, you will need to weigh it yourself. Therefore, I also provide a method for manually adding nofollow
, please note that it cannot be used together with the above code.
<a href="URL" title="Title" rel="nofollow" target="_blank">Link Text</a>
I come from China and I am a freelancer. I specialize in Linux operations, PHP, Golang, and front-end development. I have developed open-source projects such as Zdir, ImgURL, CCAA, and OneNav.