Drupal 6 Tutorial: Find the Menu Parent Item for the Page Being Viewed

ORANGE COUNTY, Calif. — If you have created a page in Drupal 6 and you need to programmatically find the page's menu parent, Drupal has a very handy function for this. In other words, you have nested your page in one of your menus so that the structure looks like this:

  • Home
    • Foo
    • Bar
  • Services
    • Sevice #1
    • Service #2

When someone is viewing page title Bar, you may want to show a hero graphic that is different when someone is viewing page title Service #1. In order to do this programmatically you can edit your node.tpl.php template file and include a function that will respond to the menu parent of the page you are viewing. The magic Drupal function is menu_get_active_trail(). Here is a sample snippet of code that you can place in your node.tpl.php file (or node type specific file by naming the file node-foobar.tpl.php where foobar is the name of your content type. Remember to clear your theme registry.

<?php

/******
* SWITCHER FUNCTION THAT RESPONDS TO THE PAGE'S PARENT MENU
*/
//Get the Page's Parent Menu Item
$menuParent = menu_get_active_trail();
//Since it returns an array, make sure to target what you are looking for
//You should print_r what menu_get_active_trail() to see what else it gives you
$menuParent = $menuParent[1]['link_title'];
//Lets run a switch statement to do something based on the menu parent like change the hero image
switch($menuParent) {
    case
"About Us":
   
$img = '<img src="'.path_to_theme().'/images/about_pic.jpg" />';
    break;
   
    case
"Services":
   
$img = '<img src="'.path_to_theme().'/images/offerings_pic.jpg" width="305" height="179" />';
    break;
   
    case
"Contact Us":
   
$img = '<img src="'.path_to_theme().'/images/clients_pic.jpg" width="305" height="179" />';
    break;
}
print
$img;
?>

It is always best to put theme specific functions like this in your template.php file in your theme's folder. For the sake of this tutorial and for quicker results for new Drupal developers we suggest throwing it in your node.tpl.php template file so that you can see what it does.

Focal55 specializes in Drupal themes, Drupal module development and general contract work related to Drupal. We are based in Orange County, California and Denver, Colorado. Contact Focal55 for your Drupal development needs.

Add a Comment