Forcing all menu links to use absolute links in Drupal 8/9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_preprocess_menu(). | |
* | |
*/ | |
function MYTHEME_preprocess_menu(&$variables) { | |
// Limit to specific menus for performance. | |
$menus = ['main', 'footer']; | |
if (isset($variables['menu_name']) && in_array($variables['menu_name'], $menus)) { | |
MYTHEME_set_menu_items_to_absolute($variables['items']); | |
} | |
} | |
/** | |
* Recursively make menu items link with absolute. | |
* | |
*/ | |
function MYTHEME_set_menu_items_to_absolute(&$items) { | |
foreach ($items as $item) { | |
$url = $item['url']; | |
if (!$url->isExternal()) { | |
$item['url'] = $url->setOption('absolute', TRUE); | |
} | |
// Recursively loop of sub-menu items. | |
if (isset($item['below'])) { | |
MYTHEME_set_menu_items_to_absolute($item['below']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment