0

I am trying to conditionally switch an entire nav menu (not nav items) when a user is logged in, but the below code changes all menus.

The menu I am switching does not have a theme location to target it's added via wp_nav_menu().

add_filter( 'wp_nav_menu_args', 'foobar' );

function foobar( $args ) {

    if ( is_user_logged_in() && $args['menu'] == 'Non-Members Area' ) {

        $args['menu'] = 'Members Area';

        return $args;
    }

}

How do I target the menu Non-Members Area?

1

There are a couple of issues with the original code. In the if statement, $args['menu'] is being set to Non-Members Area (which will then evaluate to true). It looks like you actually want to be doing an equality check there. A good way to avoid this is to use Yoda conditions.

Also, the $args array should always be returned, so it should be moved out of the conditional statement. Here's an updated version of the original code:

add_filter( 'wp_nav_menu_args', 'foobar' );
function foobar( $args ) {

    if ( is_user_logged_in() && 'Non-Members Area' === $args['menu'] ) {
        $args['menu'] = 'Members Area';
    }

    return $args;
}
  • Thanks for you response. Unfortunately, the menu does not switch to the members menu when logged in. It seems the if statement is FALSE so $args is returned unchanged. – Jason Jan 19 '17 at 5:11
  • Strange. I've double checked the code and it definitely works; Non-members see the Non-Members Area menu and members see the Members Area menu. I noticed that you corrected the conditional statement in your original question, but did you move the return statement outside of the conditional statement? Double check the menu names, they should match what's in the admin exactly. Would you add the code where you're calling wp_nav_menu()? – Dave Romsey Jan 19 '17 at 5:38

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.