JuniperStudio

Taxonomy Menu Add Class Attributes

I needed a menu based on a taxonomy for a high level sorting of blog posts. I generated a menu using the Taxonomy Menu module. This module will add an active trail based on the taxonomy term on the node.

/**
* Implements hook_preprocess_menu().
*/

function coupa_8_preprocess_(menu_id)(&$variables, $hook) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    $nid = $node->id();
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);
    if($node->getType() == 'blog') {
      $node_target_tid = $node->get('field_content_tags')->target_id;
      if ($node_target_tid != NULL) {
        $items = ($variables['items']);
        foreach ($items as &$item) {
          $menu_id = $item['url']->getRouteParameters();
          if ($node_target_tid == $menu_id['taxonomy_term']) {
            $item['attributes']->addClass('menu-item--active-trail');
          }
        }
      }
    }
  }
}

Check to see if page is a node.

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $nid = $node->id();
}

Load the node.

$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);

Check if the node is a blog post.

 if($node->getType() == 'blog') {}

Load the taxonomy ID of the node. This taxonomy is limited to 1 value.
use ->target_id method to get the taxonomy ID.

$node_target_tid = $node->get('field_content_tags')->target_id;

Iterate through the menu items.

$items = ($variables['items']);
foreach ($items as &$item) {
   $menu_id = $item['url']->getRouteParameters();
}

Add active trail with ->addClass method.

if ($node_target_tid == $menu_id['taxonomy_term']) {
$item['attributes']->addClass('menu-item--active-trail');
}