Drupal - How do I filter a menu to only show menu items translated into current language?
I managed to hide non translated menu items with the following code:
use Drupal\Core\Menu\MenuLinkInterface;
use Drupal\menu_link_content\Plugin\Menu\MenuLinkContent;
/**
* Implements hook_preprocess_menu().
*/
function MY_MODULE_preprocess_menu(&$variables) {
if ($variables['menu_name'] == 'main') {
$language = Drupal::languageManager()->getCurrentLanguage()->getId();
foreach ($variables['items'] as $key => &$item) {
$menuLinkEntity = MY_MODULE_load_link_entity_by_link($item['original_link']);
if ($menuLinkEntity != NULL) {
$languages = $menuLinkEntity->getTranslationLanguages();
// Remove links which is not translated to current language.
if (!array_key_exists($language, $languages)) {
unset($variables['items'][$key]);
}
}
}
}
}
function MY_MODULE_load_link_entity_by_link(MenuLinkInterface $menuLinkContentPlugin) {
$entity = NULL;
if ($menuLinkContentPlugin instanceof MenuLinkContent) {
list($entity_type, $uuid) = explode(':', $menuLinkContentPlugin->getPluginId(), 2);
$entity = \Drupal::entityManager()->loadEntityByUuid($entity_type, $uuid);
}
return $entity;
}
There is probably a better way but this worked for me. Got the inspiration from here: http://www.agoradesign.at/blog/add-custom-menu-item-attributes-drupal-8