knackforge
March 21, 2013
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 at the 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.,
Replace the theme name with your theme's name and clear the cache once either with drush or with the performance tab. Once done this will display the user's name in the main menu.
Note: The change of orders in the 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.
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!