Home > OS >  WordPress: Switch navigation when user is logged in.... but only one the main nav menu in the header
WordPress: Switch navigation when user is logged in.... but only one the main nav menu in the header

Time:09-19

I've got a script that works.... a bit too well. It's supposed to be when you login to the site, the main nav reflects that switch. It works, but it's only supposed to occur on the nav in the header. Instead, it changes all nav elements, no matter where they are. So I have three other menus in the footer but they all change to the same menu.

How can I just target the main nav in my header alone?

Here's the code:

function my_wp_nav_menu_args( $args = '' ) {
    if( is_user_logged_in() ) {
        // Logged in menu to display
        $args['menu'] = 80;
    } else {
        // Non-logged-in menu to display
        $args['menu'] = 25;
    }
    return $args;
    }
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

CodePudding user response:

If you check the docs for that filter you will see that the $args that come have an index 'theme_location' where you can indicate, precisely in which menus your code should run.

You need the identifier for that menu, which can be something like 'primary' or 'main_menu' - whatever the theme author(s) decided to identify the theme location for the menu.

Log/check the $args variable to obtain the ones available in your theme, and identify the one you need.

So, if your header nav's id is, 'primary', your snippet should be updated to this, to check that it only runs for that menu and leaves the others alone:

function my_wp_nav_menu_args( $args = '' ) {
    
    //If it is not the header nav menu, don't do anything
    if( $args['theme_location'] !== 'primary' ){
          return $args;
    }

    if( is_user_logged_in() ) {
        // Logged in menu to display
        $args['menu'] = 80;
    } else {
        // Non-logged-in menu to display
        $args['menu'] = 25;
    }
    return $args;
    }
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

This should work but let me know if you need more help.

  • Related