How to Add Nofollow Tag on External Links in WordPress

February 19, 2014 — 6 Comments

You means, why no-follow tag on external links? Let me explain it.

The rel=”nofollow” tag on external links ensures that the search engine indexing your site (such as Google or Bing) does not follow those links and associate them with your site’s rankings.

However, Matt Cutts says that we shouldn’t be worrying too much about which links to follow or ‘nofollow’ as Google’s search ranking algorithms are changing everyday and the old school methods of ‘fooling’ a search engine are long gone.

Add Nofollow Tag on External Links in WordPress

To add rel=”nofollow” tag on external links in WordPress you should add the following code in your functions.php:


add_filter( 'the_content', 'addNofollow_url_function');

function addNofollow_url_function( $content ) {

$regExpression = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
 if(preg_match_all("/$regExpression/siU", $content, $matches, PREG_SET_ORDER)) {
 if( !empty($matches) ) {

 $targetUrl = get_option('siteurl');
 for ($i=0; $i < count($matches); $i++)
 {

 $tag = $matches[$i][0];
 $tag2 = $matches[$i][0];
 $url = $matches[$i][0];

 $noFollow = '';

$pattern = '/target\s*=\s*"\s*_blank\s*"/';
 preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
 if( count($match) < 1 )
 $noFollow .= ' target="_blank" ';

 $pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
 preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
 if( count($match) < 1 )
 $noFollow .= ' rel="nofollow" ';

 $pos = strpos($url,$targetUrl);
 if ($pos === false) {
 $tag = rtrim ($tag,'>');
 $tag .= $noFollow.'>';
 $content = str_replace($tag2,$tag,$content);
 }
 }
 }
 }

 $content = str_replace(']]>', ']]&gt;', $content);
 return $content;
}

Or if you are afraid or using any theme framework like Genesis, Thesis, or any other framework you should use this plugin.

6 responses to How to Add Nofollow Tag on External Links in WordPress

  1. Hi Brother. I read your post.

    Brotehr i want a quistion that what is best for us. No foolow links or Do follows link in our blogs. I m new in bloging .. I read your post and your blog i realy Thank full to you.

    • MuhammadHaroon March 13, 2014 at 3:47 pm

      Well @Adeel, No follow attribute is more better than dofollow because this can save the PR juice and increase your blog PR (PageRank) effectively.

  2. Hi, It is useful post great work!

  3. very nice post, important for newbies who use wordpress

  4. Very useful information, really helpful, thanks for sharing

  5. Thanks for Share , very Helpful

Leave a Reply

*

Text formatting is available via select HTML. <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>