Site logo

[Resolved] Conditional menus (php snippets)

Home Forums Support [Resolved] Conditional menus (php snippets)

Home Forums Support Conditional menus (php snippets)

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2291052
    Toby

    Hey guys,

    I am running this lovely snippet to change the main menu shown depending on if the visitor is logged in/out.

    function wpc_wp_nav_menu_args( $args = '' ) {
    if( is_user_logged_in() ) { 
        $args['menu'] = 'Subscriber';
    } else { 
        $args['menu'] = 'Visitor';
    } 
        return $args;
    }
    add_filter( 'wp_nav_menu_args', 'wpc_wp_nav_menu_args' );

    The code works perfectly, however, I have just added a secondary navigation menu which also displays the main menu in place of the secondary menu, and this snippet is the culprit.

    Could this snippet be amended, so it only targets the main menu, leaving the secondary menu in peace?

    I have used the snippet you recommend here to hide the secondary nav when required.

    Thanks,
    Toby

    #2291216
    David
    Staff
    Customer Support

    Hi there,

    try this snippet instead:

    function db_switch_menus( $args ) {
        if( 'primary' !== $args['theme_location'] ) { 
            return $args;
        }
        if( is_user_logged_in() ) { 
            $args['menu'] = 'Subscriber';
        } else { 
            $args['menu'] = 'Visitor';
        }
        return $args;
    }
    add_filter( 'wp_nav_menu_args', 'db_switch_menus' );
    #2291667
    Toby

    Worked a charm, thank you David.

    I did have to add a ; after return $args as it threw an error without.

    May be worth amending your post for future readers with the same issue?

    The final code was:

    function db_switch_menus( $args ) {
        if( 'primary' !== $args['theme_location'] ) { 
            return $args;
        }
        if( is_user_logged_in() ) { 
            $args['menu'] = 'Subscriber';
        } else { 
            $args['menu'] = 'Visitor';
        }
        return $args;
    }
    add_filter( 'wp_nav_menu_args', 'db_switch_menus' );
    #2291853
    David
    Staff
    Customer Support

    Good spot 🙂 missing ; added.

    Glad to be of help.

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.