0

I have two menus namely : "nav-menu" and "user-menu". I just want to switch (or toggle) to a specific menu between the two menus to be primary menu whenever I visit a particular page.

For ex : If I go to some particular page then my menu programatically switches to "user-menu".

I have visited How to switch between the Primary Menus programmatically?. However, I am still not able to figure it out.

Can someone help me by giving brief explanation of the code?

0

You can try this code in specific page template

function change_primary_menu( $menu ) {
        // you can check spesific menu id using this print and after that assign in,
        // and you can also check menu location using this print too
    echo '<pre>';
    print_r($menu) ;
        echo '</pre>';

        $user = wp_get_current_user();
        //in this example im check the user role is 'user'
        if ( in_array( 'user', (array) $user->roles ) ) {
            //if yes change to user menu (19 and 21 is just example menu id)
            $menu['primary'] = 19;
        }else{
            //if not change to another menu
            $menu['primary'] = 21;
        }
    return $menu;
};

add_filter( 'theme_mod_nav_menu_locations', 'change_primary_menu', 10, 2 );
  • I tried this, but it didn't work. Was printing the Array at two places. One at random page location (I know it's because of the 'print_r' ststement). But the other one was at the menu location. I guess it might have replaced the menu object with PHP Array object. On debugging more, I found out that this '$menu' variable inside the function definition was empty Array object. – noobron Aug 15 at 5:50
  • if $menu is empty, that mean you dont have any menu location. But you say you have primary menu, so I think you have 'primary' as name of a menu location – Manyang Aug 15 at 6:38
0

I got this worked out! I used 'wp_nav_menu_items' hook to customize the links of the menu. However, it actually dosen't specifically answers my question but it solves my problem. Here's an example for the 'PROFILE' page :-

add_filter( 'wp_nav_menu_items', 'set_profile_links', 10, 2 );
function set_profile_links( $items, $args ) {
    $items = '<li ><a href="http://localhost/wordpress/index.php/dashboard">Dashboard</a></li>';
    $items .= '<li id="current-page-menu"><a href="http://localhost/wordpress/index.php/my-account">PROFILE</a></li>';
    return $items;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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