Site logo

Archived topic

Secondary Menu in sidebar and conditional logic (logged in/ logged out)

5 replies · Started by Patricia on June 26, 2018

Viewing posts 1–6 of 6

I have three menus: Logged In, Logged Out (for Primary Menu Location), and a User Dashboard Menu (set as Secondary menu location and located in the left sidebar). I used the following two code snippets to designate logged in vs. logged out for primary and to hide the sidebar for non logged in users. But my problem is that now the sidebar only displays the primary menu, not secondary menu. I'm sure I've done something wrong in the coding but can't place it.

Here it is:

1.LOGGED IN OUT PRIMARY MENU

function my_wp_nav_menu_args( $args = '' ) {
 
if( is_user_logged_in() ) { 
    $args['menu'] = 'logged-in';
} else { 
    $args['menu'] = 'logged-out';
} 
    return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

2. HIDE SIDEBAR FROM LOGGED OUT USER

add_filter( 'generate_sidebar_layout','tu_logged_out_sidebar' );
function tu_logged_out_sidebar( $layout )
{
 	if ( ! is_user_logged_in() ) {
            return 'no-sidebar';
        }

 	// Or else, set the regular layout
 	return $layout;
}

Hi there,

Is there a specific page I should be looking at?

Currently the two pages I see are all from Elementor.

Let me know :)

Leo,

Well you won't see the left sidebar menu unless you are logged in. That part of the code is working fine. Why it displays the logged in primary menu is where I'm confused.

I originally had this code in a child theme file. But that didn't seem to work at all. So, now you can find them in the code snippets plugin. You'll see the three menus I have in the appearance>menu section. I designated the User Dashboard for the secondary menu, which was working fine until I added the conditional display rules. I gave you admin permissions.

You may need to target the theme location of the menu you want to alter.

So if this code is targeting the primary menu, your code should look like this:

function my_wp_nav_menu_args( $args ) {
    if ( 'primary' === $args['theme_location'] ) {
        if ( is_user_logged_in() ) { 
            $args['menu'] = 'logged-in';
        } else { 
            $args['menu'] = 'logged-out';
        }
    }

    return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

Tom,

Thanks that was it! I just needed to target the specific theme menu location. Your code was perfect.

Awesome, glad I could help! :)

This archived topic is closed to new replies.