Automatic Nofollow links in WordPress posts

Written by pelister. Posted in Plugins, Wordpress

Nofollow links might have haunted you whenever you come across the word SEO, and search engines stressing on its importance. If you want to add nofollow to your links in wordpress posts, here is a simple solution. In fact I have come up with 2 methods.

  1. editing functions.php that resides within your theme folder  (or)
  2. plugin – just download, install and activate. (no need to edit functions.php)

First Method

Open your functions.php and add the following lines of code.

add_filter( 'the_content', 'nofollow' );

function nofollow( $content )
	return preg_replace_callback( '/<a[^>]+/', 'callback' , $content );

function 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 ) && ( strpos( $link, 'author' ) === false ) ) //check for embedded rel='author' within content.
			$link = preg_replace( '/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link );
	return $link;

I have also added optional rel=”author” checking – for plugin based author boxes that embed author info within content, so we may not accidentally replace G+ author links.

Second Method

External Links Nofollow plugin, install the plugin and activate. The same function code shown above is wrapped up into a plugin.


Compatibility WordPress 3+.

Popular Posts

Techlister© - 2012