Hide register link for administrator role users in Drupal 8

Posted on Friday, April 7, 2017

While working on Drupal 8 one of the issues you might face is you won't get "Register" link for anonymous user. And you need to create this menu item in the user menu.

But with this approach one issue, you might face is this menu item will be visible to users who has "Administrator" role. There are two solutions for this problem:

  1. Use Menu item visibility module

    With Menu Item Visibility module you can give specific permission to roles who can access menu items. This can be used to hide "Register" link for authenticated users.
  2. Alter menu with hook_preprocess_menu()

    If using a module is an overkill then simply use hook_preprocess_menu() to alter the menu items which will be visible to the user.
<?php
function alshaya_user_preprocess_menu(&$variables) {
  
// Hide particular link for the authenticated user.
  
$items $variables['items'];
  foreach (
$items as $key => &$item) {
    
// Hide register link.
    
if ($item['url']->getRouteName() == 'user.register' && \Drupal::currentUser()->isAuthenticated()) {
      unset(
$variables['items'][$key]);
    }
  }
}
?>

 

Tags

Disqus Comments