How to highlight the menu items related to the particular content type? Actually I want whenever the user visits the page related to the particular content type,it should highlight the particular menu item. Context module is the one solution for this. Is any other custom coding solution without installing any module?
1 Answer
You can use theme_menu_link function. Add this code to template.php of your theme
function themename_menu_link(array $variables) {
$path_parts = array();
$element = $variables['element'];
$sub_menu = '';
$menuName = $variables['element']["#original_link"]["menu_name"];
//Check menu name
if($menuName == 'main-menu')
{
$path_parts = explode('/',$element['#href']);
if($path_parts[0]=='node' && is_numeric($path_parts[1]))
{
$menu_load_node = node_load($path_parts[1]);
//Check node type (In our case 'article')
if($menu_load_node->type == 'article')
{
$element['#attributes']['class'][] = 'highlight';
}
}
}
if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
All links to nodes with type 'article' will have class highlight
-
it is working only for main menu i am trying to highlight the custom menu. how to do highlight custom menu? Commented Mar 31, 2017 at 10:50
-
In string if($menuName == 'main-menu') change main-menu to your menu name. Menu name You can see on menu edit page - this is Machine name of menu Commented Mar 31, 2017 at 12:49
-
When i printed the $variables variable I am not able to see the detail of custom menu.It is still referring to main menu only. Commented Apr 4, 2017 at 7:04
-
For the first output your custom menu as block on page. Maybe You have only main-menu on the page. Commented Apr 4, 2017 at 7:38
-
yes the custom menu is as block only and only 1 main menu on the page. Then, how can i implement it? Commented Apr 4, 2017 at 8:43