phpwordpress

Showing dynamic or different menus on wordpress not working in my theme


On my WordPress page, there's a primary menu that shows up at the header of all pages, but I want to show a different set of menus for pages in the route /tech-products.

Based on my research on this site, adding the following to my function.php and then setting up the menu in Appearance → Menus → Manage Locations is expected to work, but it doesn't work.

function register_custom_menus() {
    register_nav_menus(array(
        'primary' => 'Primary Menu',
        'tech_products_menu' => 'Tech Products Menu',
    ));
}
add_action('init', 'register_custom_menus');

Solution

  • I've been able to get this to work. Adding the following to my header.php worked, although I found this in a linked file named navbar-collapse-bootstrap5.php, which is where my navigation is output.

    <?php
        $uri = $_SERVER['REQUEST_URI'];
        $menu_location = (strpos($uri, '/tech-products') === 0) ? 'tech_products_menu' : 'primary';
        
        wp_nav_menu(
            array(
                'theme_location'  => $menu_location,
                'container_class' => 'collapse navbar-collapse',
                'container_id'    => 'navbarNavDropdown',
                'menu_class'      => 'navbar-nav ms-auto',
                'fallback_cb'     => '',
                'menu_id'         => 'main-menu',
                'depth'           => 2,
                'walker'          => new Understrap_WP_Bootstrap_Navwalker(),
            )
        );
        ?>