WordPress Tricks: Automatic Add nofollow Tag for External Links

When we write article, we often uses some external links to extent our content. These links will help other websites build search engine weightiness. If you don’t want to help your competitors, you should add “nofollow” to these links. One idea is to add rel=”nofollow” on each links manually. But, it will be a tough task. Could we find an automatic solution to solve this problem?

The functions.php is the function library in a wordpress theme. We can add some codes in this file to help us add rel=”nofollow” for each external links. The following is the source code we need.

add_filter('the_content', 'wp_auto_nofollow'); 
function wp_auto_nofollow($content) {
	return preg_replace_callback('/<a>]+/', 'wp_auto_nofollow_callback', $content);
}
function wp_auto_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;
}

Then you need to empty all caches and all the external links will have a “nofollow” tag. Sure, adding nofollow tag is not always a good idea for SEO. Do it only when you can make sure this is good for your website.

Leave a Reply

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