Overview

When building sites, often we want to add a menu item that links to a user's account page. The problem is, Drupal menus do not allow for dynamic paths to be used for menu items. User account pages are dynamic paths with the format user/[UID]. One solution is to link to the path /user, which will redirect the user to their account page. There are two issues with this however. The first is that the /user path is available to both anonymous and authenticated users. For anonymous users, they are shown the user/login page, giving them the option to sign in. Authenticated users are shown their account page. However, the text is the same for both links, so if you set the menu item text to be 'My Account', both anonymous users and authenticated users will see the same text, whereas it may be preferable to show 'Sign In' to anonymous users, and 'My Account' to authenticated users.

One way around this is to create a new static menu link that redirects to the dynamic page in question. This works, however we then run into another issue in that when the user is on the redirected page, the 'My Account' page does not receive the .active class, as the menu item is not highlighted.

Solution

To get around the above issue, I usually create a new Drupal path for 'My Account' as follows. The following uses hook_menu(), and redirects the user to their account page:

span class="st0">'my_account''title' => 'My Account',
    'page callback' => 'my_module_my_account_callback',
    'access callback' => 'user_is_logged_in''user/' . $user->uid);
}

With the above code, when a user accesses the 'my_account' path, they are redirected to their account page. The path 'my_account' is a static path, so it can be added to any Drupal menu. The final bit of code to get this working adds a class of .active to any menu items that lead to 'my_account', when the user is on their own user page. This function is a preprocess hook for altering menu items. It should be named [MODULE/THEME NAME]_preprocess_menu_link()

span class="st0">'element'];
  // Set 'My Account' link to active on user page
'#href'] == 'my_account''user/' . $user->uid)
  {
    $element['#localized_options']['attributes']['class'][] = "active";
  }
}

After adding the above code to a module, the menu link will show as active when the user is on their account page. Now we can link to the 'my_account' page in any drupal menu, and have it redirect the user to their account page, while still showing the menu item as active.