Drupal Tips: How to add dynamic login / logout link to your primary menu

The Drupal Menu System handles both the navigational system (visible menus and links) as well as the Drupal callbacks in the back end. The menu links listed on the header of a Drupal site is normally the primary menu or the secondary menu. These menus are sets of static links that you create via the Drupal admin interface. However sometimes it is useful to have a login / logout link in the primary or the secondary menu depending on whether the user is logged out or logged in. Here is how you add this.

Add the following piece of code to your preprocess_page hook in your module (modulename_preprocess_page()) or in your theme template.php (themename_preprocess_page())

  if ($user->uid != 0) {
    $new_links['account-link'] = array(
      'attributes' => array('title' => 'Account link'), 
      'href' => 'user', 
      'title' => 'My Account'
    );
    $new_links['logout-link'] = array(
      'attributes' => array('title' => 'Logout link'), 
      'href' => 'logout', 
      'title' => 'Logout'
    );
  } else {
    $new_links['login-link'] = array(
      'attributes' => array('title' => 'Login link'), 
      'href' => 'user', 
      'title' => 'Login'
    );
  }
  $vars['secondary_links'] = array_merge_recursive($vars['secondary_links'], $new_links);


The above snippet will add a 'My Account' and a 'Logout' link for logged in users and 'Login' link for anonymous users to the secondary_links. If instead you wanted to add the links to your primary links you can replace the last line with

  $vars['primary_links'] = array_merge_recursive($vars['primary_links'], $new_links);


You will also have to make sure that none of the caching mechanisms set up on your site caches this across roles.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options