0

I am looking to add nofollow to specific internal paths when they appear within text anywhere in the posts.

I tried using the text filters but I only get the options to either nofollow all links within a post body or nofollow all external links.

What I am trying to achieve is to nofollow all links following this pattern (/user/* ) when they appear within text body.

What are my options? Custom filter? or a preg replace through preprocess. I will appreciate a bit detailed explanation as I am new to programming.

Thanks in advance.

1 Answer 1

1

Since you want to add this attribute only to custom URLs (those matching /user/*) within your content, you might have to write custom code, as I'm not aware of any module which does this.

You could use hook_preprocess_field() and then execute a regular expression to match your pattern and add the rel="nofollow" attribute. However, this could be highly inefficient, as you have to do it every time you render a node, besides the fact that parsing HTML with regular expressions is not a bullet-proof solution.

Here it's a very simple example that just adds rel="nofollow" to all links in the body field (you will have to adapt it to use your own regular expression).

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
     $markup = $variables['items']['0']['#markup'];
     $variables['items']['0']['#markup'] = preg_replace('/href=/', 'rel="nofollow" href=', $markup);
  }
}

Another alternative would be using the Path Nofollow module, that does something similar:

Specify paths on which a metatag is added to prevent search engines from indexing the page.

So you could specify the path /user/* and it will add a metatag in the head of your html <meta name="robots" content="noindex">. As I said, not exactly the same, but it might help or complement your goal.

2
  • This module doesn't solve the problem as I would prefer to fix them within the body rather than letting the crawlers even get to the page. I found something similar but it doesnt work for links in the body. Do you have any tips on how to modify it? function mytheme_preprocess_link(&$variables) { if (preg_match('/(user|go\/[0-9]*$)/i', $variables['path'])) { $variables['options']['attributes']['rel'] = 'nofollow'; } }
    – KBS
    Jul 27, 2015 at 23:28
  • That's because your my_theme_preprocess_link function works only for links generated by Drupal. But in your case, your links are IN your body field (they are manually created with HTML tags, either by yourself or by a WYSIYWG editor). So, you'll need to do the preprocess to your body field instead.
    – typologist
    Jul 28, 2015 at 2:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.