I would like to display a different menu in the same theme_location depending on some condition. I’m wondering if this is possible and if so how?
I would like to avoid registering an additional theme_location, since it would actually just be placed in the same location and having two locations in the same spot might confuse the user.
I tried naming another menu in the first if statement, but I just got the same menu as in the else.
My code:
<?php
if ( preg_match ('#^/company/#', $_SERVER['REQUEST_URI']) ) {
# get me another menu in the same theme location as below
}
else {
wp_nav_menu( array( 'menu' => 'Primary Menu', 'theme_location' => 'primary' ) );
}
?>
Do I have to register two theme_locations or is this possible with one?
1 Answer
Ok I managed to fix this. Posting the answer here for anyone interested.
I didn’t quite understand that register_nav_menus only registeres menu locations.
This is the code I used which does conditionally use different named menus in the same location. For this to work, you have to use the exact name specified when creating the menus. Or, as I did, create them programmatically to make sure they always exists and are named correctly.
<?php
if ( preg_match ('#^/company/#', $_SERVER['REQUEST_URI']) ) {
wp_nav_menu( array( 'menu' => 'company-primary', 'theme_location' => 'primary', 'fallback_cb'=> false ) );
}
else {
wp_nav_menu( array( 'menu' => 'private-primary', 'theme_location' => 'primary', 'fallback_cb'=> false ) );
}
?>
I used this code to set up some default menus:
// Set up default menus
$private_menu_exists = wp_get_nav_menu_object( 'private-primary' );
if( !$private_menu_exists){
$menu_id = wp_create_nav_menu( 'private-primary' );
}
$company_menu_exists = wp_get_nav_menu_object( 'company-primary' );
if( !$company_menu_exists){
$menu_id = wp_create_nav_menu( 'company-primary' );
}