1

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.

  • isn't the menu cached by drupal? wouldn't that be a bad thing to do? – saadlulu May 20 '12 at 10:16
4

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' ;)

  • 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'); " – uwe May 21 '12 at 1:44

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.