Is menu_set_active_trail the way to go if I need to change user/* page titles?

by sbrattla   Last Updated February 11, 2019 09:07 AM

I've had the pleasure of spending a bit of time trying to change the page titles (the one you get via drupal_get_title()) of user, user/register and user/password. It appears that this is doable in a not so consistent manner by either :

  1. Invoke drupal_set_title from e.g. hook_form_user_register_form_alter, but as this form may be added to any other page which already has a title I assume this may come with undesired side effects.

  2. ...or change $vars['title'] in a preprocess function, but this doesn't really change the page title. It just changes the $title variable which is injected into the template. Other modules (e.g. metatag) would still use the default title.

  3. ...or use hook_menu_alter to set do $items['user']['title callback'] = 'user_title';, and from there set the page title via function user_title. It seems, however, that this does not work as long as there is a menu item in some menu that links to user. In that case, the user page will be given the title of the menu item of the most preferred menu :

    // Try to retrieve a menu link corresponding to the current path. If more
    // than one exists, the link from the most preferred menu is returned.
    $preferred_link = menu_link_get_preferred();
    $current_item = menu_get_item();
  1. ...or use hook_init to invoke menu_set_active_trail from there. This ensures that the active trail is set, and thus that's the trail which will be used unless other modules explicitly invoke menu_set_active_trail_again. The drawback with this one is that some modules (e.g. the user module) will invoke menu_set_active_item and menu_execute_active_handler again - and thus setting a custom page title in this case fails.

Number 1 and 2 is either flawed or has side effects. While 3 seemed to be the way to go it appears that any menu item which links to the current path will override any title which otherwise would be set by the title callback. Number 4 works most of the time, but not when you go to user as a logged in user.

So, I've now implemented hook_menu_site_status to (1) check which path the user is attempting to access and (2) from there invoke menu_set_active_trail with a custom trail so that I override any trail generated by Drupal based on existing menu items (#3 above). This works even if a module calls menu_execute_active_handler again.

Now, although this works, it feels a bit "brute force"-ish. Is this really the way to change a page title when a menu item links to the same page and thus apparently has the last word on what a page title should be?. It feels very convoluted.

Tags : 7

Related Questions