Drupal - Open a link in a new tab in the menu

In my case I utilized hook_link_alter() to accomplish this. Situation: in my menu links, I only need Contact Us to open in a new tab.

<?php
function MYMODULE_link_alter(&$variables) {
  if (!$variables['url']->isRouted()) {
    $uri = $variables['url']->getUri();
    // Only want the Contact Us to open in new tab.
    if ($uri == 'base:contact-us') {
      $variables['options']['attributes'] = ['target' => '_blank'];
    }
  }
}

This one works fine for ALL external links:

function MYMODULE_link_alter(&$variables) {
  if ($variables['url']->isExternal()) {
    $variables['options']['attributes'] = ['target' => '_blank'];
  }
}

Menu target module in dev version for D8 but you can check.

Allows privileged users to choose wether or not to open menu items in a new window. When enabled, users who have access to add or edit menu items, are provided the possibility to choose if the menu items should be opened in a new window or in the same window.

Tags:

Navigation

8