Sometimes you want to know the top-level menu item of the current page (eg as a header for a submenu).

This is easy enough to determine with some PHP code, but how can you display the value?

To get and display the name of the top-level menu we need to execute some PHP in an article or module. There are a number of extensions that address this; I use the Sourcerer extension [1] but others should support a similar process.

Note that the Sourcerer extension required PHP 5.3 and will not work on 5.2.

In the Article

The Sourcerer extension adds an 'Insert Code' article button

You might get a default code skeleton depending on your setup - the PHP code you need is:

$m = JSite::getMenu()->getActive();
if ($m->level > 1):
$pi = $m->parent_id;
$pi = $m->id;
$m2 = JSite::getMenu()->getItem($pi);
echo $m2->title;
That's all. Save and close and you should see the name of the parent menu.

Here is the result of adding the code to this page Blog .


Code breakdown

  • It's PHP code, so we wrap it in '<?php' and '?>'.
  • Get the active menu item - this is a menu object.
  • If the menu item is second level (or greater), get its parent menu item, otherwise just get the menu id
  • Get the menu item associated with this menu id (which will be the same as the active item for top level menu items, but will be the parent of second level menu items).
  • Print the title of the menu.

This code assumes a two level menu structure. If you have more levels you will need to adjust the code accordingly (potentially recursing up a menu tree).

Other uses

You can put the same code in a Custom HTML module and display it anywhere.