Only show menu if the current page is in menu

Is it possible to conditionally display a menu based on whether the current page is present in the menu?

Related posts

Leave a Reply

1 comment

  1. You can use the following code. Loop through every item, in every menu, and check if the item exists. If it does, display the menu and move on to the next menu.

        <?php 
        // get array of nav menus
        $menus = wp_get_nav_menus(); 
    
        //get current page URL
        $uri = $_SERVER['REQUEST_URI'];
    
        //loop through each menu looking for current page
        foreach($menus as $menu)
        {
            //get menu items from ith menu in loop
            $items = wp_get_nav_menu_items( $menu->term_id );
    
            //loop through each item in menu to check for 
            foreach($items as $item)
            {
                if( strpos($item->url, $uri) !== false )
                {
                    //display menu
                    wp_nav_menu( array('menu'=>$menu->term_id) );
    
                    //current menu done, check next menu
                    break;
                }
            }
        }
        ?>
    

    All relevant WordPress functions usage can be found in the codex, or via Google Search.