Tell me more ×
Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

I have a "new comments" menu item in the user-menu that is generated by a view. I would like to change the title of the menu to include the number of new comments.

I tried using hook_menu_alter without success. I cleared the cache and rebuilt the menu using the devel function.

function newcomments_menu_alter(&$items){
  $items['newcomments']['title'] = '5 New Comments';
} 

When I add a menu item with hook_menu() I can dynamically change the title with a custom "title callback" function. But I can't figure out what the "page callback" is to display the view.

share|improve this question
isn't the menu cached by drupal? wouldn't that be a bad thing to do? – saadlulu May 20 '12 at 10:16

1 Answer

up vote 1 down vote accepted

Views doesn't implement hook_menu() to add it's items, it uses the menu link API directly to add links. This makes it a bit trickier to do what you want as hook_menu_link_alter() isn't necessarily called when the caches are flushed, but only when the link is edited via the admin UI.

The links in menus don't even necessarily go through theme_menu_link() so you can't override the title at the theme level with that hook. Instead the only way I could find to do it was to implement hook_preprocess_link(), check the path, and change the title.

It's not a very pleasing solution, as theme_link() seems far too generic a place to be hooking into to change just one link title, but it might do the trick:

function MYMODULE_preprocess_link(&$vars) {
  if ($vars['path'] == 'newcomments') {
    $num_comments = MYMODULE_num_comments();
    $vars['text'] = format_plural($num_comments, '1 New Comment', '@count New Comments');
  } 
}

The only problem is that if there are other links on the page that point to the same URL their title will also be changed. Hopefully this can be a 'feature' rather than a 'bug' ;)

share|improve this answer
thanks a bunch. I got it working with hook_menu() and using a custom "page callback" function. The function returns the view with "return views_embed_view('newcomments2', 'page_1'); " – MotoTribe May 21 '12 at 1:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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