4

Recently I've been asked by a SEO-managing person to copy the text of all links within main menu into their title attribute. As my menu is run by OM Maximenu and contains mostly Views, it was relatively easy to add it in corresponding view, but I started to wonder if there's a way to globally alter links in such a way. It would have to be performed in PHP level (template.php or a module). I haven't found a hook though like "drupal_link_alter", except for some old Drupal 5 function?

Any insights?

2

A lot of links end up going through theme_link() at some point (even those that go through the l() function by default); so providing a preprocess function for that theme, that adds a title to any link that doesn't already have one, would be a very good start:

function MYTHEME_preprocess_link(&$vars) {
  // If there is already a title set, and it's not empty, we don't need to continue.
  if (isset($vars['options']['attributes']['title']) && !empty($vars['options']['attributes']['title'])) {
    return;
  }

  // Otherwise we use the link text as the title.
  $vars['options']['attributes']['title'] = strip_tags($vars['text']);
}

This won't catch links that are outputted directly in HTML, or don't go through l()/theme_link(), but I think you'll struggle to intercept those anyway (it would require some DOM parsing or ugly regex).

  • Be careful all ye who use that snippet that - if the a tag contains img or other markup, that markup will be all copied into title attribute. – Artur Jun 9 '12 at 23:17
  • @Artur good point...it's an easy fix though I've updated the answer – Clive Jun 9 '12 at 23:47
  • No wonder your badges don't fit into the pockets anymore ;-) – Artur Jun 10 '12 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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