PHP code to get active menu item ID in Joomla

When you need to get your active menu item ID in Joomla to display some specific content for only that menu item or just to show the ID of the menu item, you'll need to edit your index.php file in your templates folder (or use a third party plugin to add a PHP module somewhere in your site) and insert a piece of code where you wish to display the active menu item ID.

Here's the code to retrieve active menu item ID in Joomla:

<?php
 $currentMenuId = JSite::getMenu()->getActive()->id ;
echo "Your menu item ID is: $currentMenuId"; 

?>

And to display something only when your desired menu item is clicked (active), you can use:

<?php 

 $currentMenuId = JSite::getMenu()->getActive()->id ;
 if ($currentMenuId == "2") echo '<p>This is only visible with menu item which has ID 2.</p>';
?>

I used this last piece of code to add a http header refresh to a Joomla page so that when one certain menu item is clicked, the user automatically gets redirected after a period of time to another page. The code below needed to be inserted inside index.php <head></head> section:

<?php
 $currentMenuId = JSite::getMenu()->getActive()->id ;
 if ($currentMenuId == "2")
 echo '<meta http-equiv="refresh" content="63;url=http://www.theotherpageyouwanttoredirectto.com"> ';  ?>

 

About me

Iinstructor of robotics (LEGO Mindstorms), computer teacher, IT support, web dev, currently studying cyber-physical systems engineering.

If you found a solution here, would you consider donating $25,000 for my next project?

Just kidding, 1$ would do fine.

Hope you found what you needed. Thanks for stepping by.