$menu = wp_get_nav_menu_items($menu_id,array( 'posts_per_page' => -1, 'meta_key' => '_menu_item_object_id', 'meta_value' => $post->ID // the currently displayed post )); var_dump($menu->ID);
Current wp_nav_menu item: The snippets story
I needed to retrieve the current wp_nav_menu item connected to the currently requested page/post in WordPress. I found some solutions going through the hole menu-tree, comparing each items object-id with the current post-id. But, since menu items are post-types, you are able to use all the WP-Query-params with wp_get_nav_menu_items, even a meta-query. The code above selects all menu_items which are connected to the current post, from the menu you specify via $menu_id.
The only drawback is that two menu-items, linked to the same post, would both be returned without you knowing which was actually clicked. However thats the same with all the other solutions I found.
One thought on “Current wp_nav_menu item in WordPress”
Thanks for sharing this snippet. It really helped me out.