only show translated menu items into current language (Drupal 8)

function MY_THEME_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'brancott-header-menu') {
   $language = Drupal::languageManager()->getCurrentLanguage()->getId();

    foreach ($variables['items'] as $key => &$item) {
      $menuLinkEntity = sapient_brancott_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]);
          continue;
        }
      }
   
    foreach ($variables['items'][$key]['below'] as $key_child => &$item_child) {
      $menuLinkEntity = sapient_brancott_load_link_entity_by_link($item_child['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]['below'][$key_child]);
        }
      }
    }

    }
  }
}

function MY_THEME_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;
}

Comments

Popular posts from this blog

Solved Drupal Interview Questions

A List of the Best Drupal SEO & Social Media Modules