Not able to get current menu ID

I’m trying to get the current menu item ID. I hve found one thread that has put me on the right track: How to get current-menu-item title as variable?

This is the code I use in my function.php file:

Read More
add_filter( 'wp_nav_menu_objects', 'current_wp_nav_menu_object' );

function current_wp_nav_menu_object( $sorted_menu_items )
{
   foreach ( $sorted_menu_items as $menu_item ) {
        if ( $menu_item->current ) {
            $GLOBALS['current_menu_title'] = $menu_item->title;
            $_SESSION['current_menu_title'] = $menu_item->title;
            break;
        }
    }
    return $sorted_menu_items;
}

But there is one annoying problem.
The data stores is always the last clicked menu item, not the current clicked menu item.

Let’ssay I have the following menu items:

  • Item 1
  • Item 2
  • Item 3
  • Item 4

(I use echo $_SESSION['current_menu_title'] to see the result)

Clicking the menu items in the following order, gives me the following results:

Item 1 -> no output
Item 2 -> outputs Item 1  
Item 4 -> outputs Item 2  
Item 1 -> outputs Item 4  

Why isn’t the current clicked menu item outputted?

Related posts

Leave a Reply

1 comment

  1. As far as I’ve seen a menu object does not have the ‘current’ property, does it? Not that I ever seen it, at least. So you can get close to what you’re asking by comparing the current post/page ID (get_the_ID()) with the items’ object_id property, when they match – boom! you got your currently selected menu.

    function wpse25992_store_current_id( $items, $menu, $args ) {
        foreach ( $items as $key => $item ) {
            // this is the currently displayed object
            if ( $item->object_id == get_the_ID() )
                $_SESSION['current_menu_title'] = $item->title;
        }
    
        return $items;
    }
    add_filter( 'wp_get_nav_menu_items', 'wpse31748_exclude_menu_items', null, 3 );