In wp_nav_menu i use for the menu, with custom walker, i can get the $depth parameter in the start_el function

function start_el(&$output, $item, $depth, $args) 

but, outside this wp_nav_menu(), how can i get the depth of the menu for the clicked item ? For instance :

  • Home
  • level1menuelement1 -level2menuelement1 (first element of first submenu) -level2menuelement2 (second element of first submenu)
  • level1menuelement2
  • ...

In that case, i want to know if my post is in a level 1 or not, to display a specific block or not.

Is there a codex function allowing to facilitate the retrieving of this depth or is it achieved programmatically ?


  • 2
    Do you need this to work for CSS and/or Javascript or for PHP?
    – s_ha_dum
    May 17, 2013 at 16:41
  • I didn't even think of a javascript solution until you mentioned it. It could do the trick (with the "current-menu-item" positioning). I'll check into that. Though it might be a "dirtier" or rather less clean solution than a php one : with js i would only hide the block.
    – Overdose
    May 21, 2013 at 8:09
  • if ($j('.current-menu-ancestor').length == 0){$j('#myblock').hide();} This works for me. But if you have a php solution, i'll be glad to have it for learning purpose.
    – Overdose
    May 21, 2013 at 8:15
  • Given that you want to know what is "clicked" there is no real PHP solution, unless by "clicked" you mean something like "the page I am on".
    – s_ha_dum
    May 21, 2013 at 12:41
  • Exactly. Let's say i've got a page 1 called when i click on level1menuelement1 and a page 2 called for level2menuelement1. Then, when i'm on page 1, i'm on the top level menu, so i hide in js (or doesn't display in php) the specific block, but when i'm on page 2, i'm not on the top level menu so i display (not hide) the block. I asked this since i didn't see anything usable related to the corresponding menu element in the query for a page.
    – Overdose
    May 21, 2013 at 12:51

1 Answer 1


how to get the relation between the page and the menu item ? = is there a WP function telling this page is linked to this menu item which has or hasn't a parent

Inside the walker, inside the start_el method (which you mentioned), $item->object_id is the page ID.

Otherwise, you need to pull the menu...

$locations = get_nav_menu_locations();
$nav_items = wp_get_nav_menu_items($locations['your-menu-location']);

... and loop over that array to match up the current page ID with the object_id in $nav_menu data... if I understand you and I am still not sure that I do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.