|
Nov 12
2009
|
Finding the top menuPosted by: Bill Tomczak on Nov 12, 2009 |
|
I was recently asked if there was a way to get the topmost menu item in which a page sits. Let's say you have a menu like this:
Item 1
--Item 1.1
--Item 1.2
----Item 1.2.1
Item 2
--Item 2.1
--Item 2.2
Let's say you wanted to do something special with all the menus in the 'Item 1' tree and something slightly different for all the items in the 'Item 2' tree. You'd want to know which tree you were on. Here is a bit of simple php code you can use the get the top most menu item no matter where in the navigation you are (see php 4 version further down):
$menu = JFactory::getApplication()->getMenu();
$active = $menu->getActive();
$top = $active ? $menu->getItem($active->tree[0]) : null;
The variable $top will be the top menu item object from wherever you are. If you are at 'Item 1.2.1', $top will have all the information for 'Item 1'. If at 'Item 2.1' it will be 'Item 2'. Among the useful bits of information in any menu item object:
$top->id
$top->name
$top->alias
'id' is the menu item id seen as 'Itemid' in a raw Joomla URL and in the menu item manager.
Note that the above code will only work in php 5. If you are still running under php 4, upgrade now! But seriously - if you must use php 4, use the following variation on the above code:
$app =& JFactory::getApplication();
$menu =& $app->getMenu();
$active =& $menu->getActive();
if ( $active ) {
$top =& $menu->getItem($active->tree[0]);
}
else {
$top = null;
}



Subscribe to this site's RSS feed