How to modify Log In or Log Out menu links in Drupal

Components

Log In and Log Out menu links, which are located in the User account menu, are provided by the User module found in the Drupal core. You cannot change these labels through the interface, but only through code.

You can do this by altering the class set for the user.logout menu link:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function MY_MODULE_menu_links_discovered_alter(&$links) {
  if (isset($links['user.logout']['class'])) {
    $links['user.logout']['class'] = 'Drupal\MY_MODULE\Plugin\Menu\MyLoginLogoutMenuLink';
  }
}

and then it is necessary to extend the appropriate class and override the getTitle() method:

<?php

namespace Drupal\MY_MODULE\Plugin\Menu;

use Drupal\user\Plugin\Menu\LoginLogoutMenuLink;

/**
 * Defines the MyLoginLogoutMenuLink class.
 */
class MyLoginLogoutMenuLink extends LoginLogoutMenuLink {

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('My Log out');
    }
    else {
      return $this->t('My Log in');
    }
  }

}

In this way, you can modify any other link that is provided by any contrib or core module.

If the title of the link is provided directly as a string and not through a class, then it is sufficient to just change the title in the hook:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function MY_MODULE_menu_links_discovered_alter(&$links) {
  if (isset($links['user.page']['title'])) {
    $links['user.page']['title'] = 'My profile';
  }
}

The above example will change the title of the user.page link from My account to My Profile.

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in PHP, JavaScript, Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.