Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Forcing all menu links to use absolute links in Drupal 8/9
<?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
You can’t perform that action at this time.