Skip to main content
knackforge blog knowledge base

Display Current user's name in main menu

Recently I had the need to display the currently logged in user's name in the main menu region. The requirement was so simple, for non-logged in users the site should just show the main menu, but for logged in users it must display their name as the first item in the main menu.

At initial glances I trusted that Drupal's inbuild would have got something to do with this, latter after exploring I found I was wrong. I wanted not to do this with any custom modules and spoil my own site nor wanted to do things with any hacks. The simplest thought that reached my mind was to do something in template level.

Main menu is something which every page in the site will display (Exception handling for admin related pages), hence I thought to make use of theme_preprocess_page  in the current theme's template.php file. The below shared code will display the logged in user's name as first item in the main menu.,

  1. function themeName_preprocess_page(&$variables, $hook) {
  2.   /*Sets the username in the main menu if logged in*/
  3.   if($variables['logged_in'] == 1) {
  4.     $main_menu = $variables['main_menu'];
  5.     unset($variables['main_menu']);
  6.     $variables['main_menu']['menu-username'] = array(
  7.       'title' => $variables['user']->name,
  8.     );
  9.     $user_name = $variables['main_menu'];
  10.     $variables['main_menu'] = $user_name + $main_menu;
  11.   }
  12. }

Replace the themeName with your theme's name and clear the cache once either with drush or with performance tab. Once done this will display the user's name in the main menu.

Note: The change of orders in main menu will not change the position of the user's name, because we unset() the whole main menu and then add them to the username. This being the case I can assure no CSS flaws or misplacement of the username in the main menu.