Add rel nofollow to all external links in the node body and comment body

For for node body field use below code:

/**
* Override or insert variables into the node template.
*/
function template_preprocess_node(&$variables) {

  /* Add nofollow */
  if(isset($variables['content']['body'][0]['#markup'])) {
    $html_dom = filter_dom_load($variables['content']['body'][0]['#markup']);
    $variables['content']['body'][0]['#markup'] = nofollowed($variables['content']['body'][0]['#markup'], $html_dom->getElementsByTagName('a'), $html_dom);
  }

}

/* Function to add rel nofollow to external link only */
function nofollowed($str, $tags, $html_dom) {
  if(!is_array($tags)) {
    foreach ($tags as $tag) {
      $this_tag = $tag->getAttribute('href');
      if (0 !== stripos($this_tag, '/') && 0 !== stripos($this_tag, url('', array('absolute' => TRUE)))) {
        $tag->setAttribute('rel', 'nofollow');
      }
    }
  }
  $str = filter_dom_serialize($html_dom);
  return $str;
}

And for comment_body field use below code:

/**
* Override or insert variables into the comment template.
*/
function template_preprocess_comment(&$variables) {

  /* Add nofollow */
  if(isset($variables['content']['comment_body'][0]['#markup'])) {
    $html_dom = filter_dom_load($variables['content']['comment_body'][0]['#markup']);
    $variables['content']['comment_body'][0]['#markup'] = nofollowed_comment($variables['content']['comment_body'][0]['#markup'], $html_dom->getElementsByTagName('a'), $html_dom);
  }

}

/* Function to add rel nofollow to external link only */
function nofollowed_comment($str, $tags, $html_dom) {
  if(!is_array($tags)) {
    foreach ($tags as $tag) {
      $this_tag = $tag->getAttribute('href');
      if (0 !== stripos($this_tag, '/') && 0 !== stripos($this_tag, url('', array('absolute' => TRUE)))) {
        $tag->setAttribute('rel', 'nofollow');
      }
    }
  }
  $str = filter_dom_serialize($html_dom);
  return $str;
}

This is useful for example, we only allow dofollow links only on signature. I use this solutions on Replr.


Author: danpros

A self-proclaimed geek, business owner, and part-time blogger.

Comments on “Add rel nofollow to all external links in the node body and comment body”