I'm trying to override the HTML output of a single menu_link only when the user is anonymous. The following code is based on this by deskulu developers.

function MYTHEME_menu_tree__secondary(&$variables) {
  $variables['tree'] = i18n_menu_translated_tree('user-menu');
  if (user_is_anonymous()) {
    $children = element_children($variables['tree']);
    foreach($children as $index => $id) {
      $classes = ['btn', 'navbar-btn'];
      if ($index == count($children) - 1) {
        $classes[] = 'btn-warning';
        $variables['tree'][$id]['#localized_options']['attributes']['class'] = $classes;
        $element = $variables['tree'][$id];
        $output = l($element['#title'], $element['#href'], $element['#localized_options']);
        return '<li' . drupal_attributes($element['#attributes']) . '><div>' . $output . "</div></li>\n";
  return render($variables['tree']);

The result, however, is a correct rewrite of the single link but the disappearance of the others.

Also, I'm unable to print with dpm() the $variables['tree'] object so it's a bit difficult to debug.

  • You should remove the "return" statement at the end of the "if" inside the "foreach" loop. You are returning some markup as soon as you find the item to overwrite, instead of returning the whole menu tree after the loop has finished.
    – dinopmi
    Nov 14 '16 at 13:49
  • Hi @dinopmi, the problem is that I don't know where to "store" the item override, because, even if I remove the return, I'm not able to use dpm() in order to visualise the structure of $variables['tree'].
    – Kropot
    Nov 15 '16 at 8:09

Your Answer

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

Browse other questions tagged or ask your own question.