Skip to content

Instantly share code, notes, and snippets.

@joelsteidl
Created November 5, 2020 15:47
Show Gist options
  • Save joelsteidl/26d9330a1c7994c59c5ebd2f7d5bb49f to your computer and use it in GitHub Desktop.
Save joelsteidl/26d9330a1c7994c59c5ebd2f7d5bb49f to your computer and use it in GitHub Desktop.
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