Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
This code can be used to to add the nodes taxonomy term names from a chosen vocabulary as css-class to every menu item. This can be used to hide certain menu items with css/javascript depending on which terms a node with menu entry is assigned to.
Put this code in template.php
function YourThemeName_menu_item_link($link) {
if (empty($link['localized_options'])) {
$link['localized_options'] = array();
}
if (preg_match('/^node/',$link['href'])) {
//get node id
$nid = explode("/", $link['href']);
$nid = $nid[1];
$node = node_load($nid); // cached
$desired_vocab = 2; // only print terms in this vocab
// print '<pre>'. $nid. check_plain(print_r($node, 1)) .'</pre>';
// if the term does not exist we're done
if (is_array($node->taxonomy)) {
foreach ($node->taxonomy as $term) {
if ($term->vid == $desired_vocab) {
$taxonomy_class = strtolower($term->name);
}
}
}
}
if (empty($link['localized_options']['attributes']['class'])) {
$link['localized_options']['attributes']['class'] = $taxonomy_class .' menu-'. $link['mlid'];
}
else {
$link['localized_options']['attributes']['class'] .= $taxonomy_class .' menu-'. $link['mlid'];
}
//print '<pre>'. check_plain(print_r($link, 1)) .'</pre>';
return l($link['title'], $link['href'], $link['localized_options']);
}
Comments
Great
Thank you!