Archived topic
Conditional menus (php snippets)
3 replies · Started by Toby on July 22, 2022
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
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' );
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' );
Good spot :) missing ; added.
Glad to be of help.