In WordPress
, I want to display a different menu on the front page than on all other pages (without plugin). I'm using a theme I created myself.
This is the code:
functions.php
register_nav_menus(
array(
'menu-1' => esc_html__( 'Main navigation', 'theme' ),
'menu-2' => esc_html__( 'Sub Menu', 'theme' ),
'menu-3' => esc_html__( 'Footer - Navigation', 'theme' ),
)
);
function theme_wp_nav_menu_args( $args = '' ) {
if( is_front_page() ) {
$args['menu-1'] = 'Main navigation - front page';
} else {
$args['menu-1'] = 'Main navigation - sub page';
}
return $args;
}
add_filter( 'wp_nav_menu_args', 'theme_wp_nav_menu_args' );
header.php
(dynamically loaded into all pages)
<?php
wp_nav_menu(
array(
'theme_location' => 'menu-1',
'menu_id' => 'primary-menu',
)
);
?>
The strange thing is, this code worked on localhost
. After uploading it to the server and a series of changes in the WordPress
dashboard, it stopped working.
I tried to recreate the process, but without success. So now I'm wondering, is some thing incorrect in my code? What am I missing?
EDIT:
I tried different suggestions (thank you all, so far!).
If I put this in my HTML
, WordPress will always use the footer navigation as main navigation, even though in the dashboard, footer is clearly set as such - and only such:
if( is_front_page() ) {
wp_nav_menu(array('menu'=>'menu-1','menu_id'=>'primary-menu'));
} else {
wp_nav_menu(array('menu'=>'menu-2','menu_id'=>'primary-menu'));
}
I find that weird, because in functions.php
, footer is menu-3
. But this code doesn't mention menu-3
anywhere.
By using this in my HTML
, the main navigation shows as main navigation and footer only as footer:
wp_nav_menu(
array(
'theme_location' => 'menu-1',
'menu_id' => 'primary-menu',
)
);
I tried vicky's suggestion for my functions.php
, but I keep having the same issue that the same main menu is used for front page and other pages...
'Main navigation - front page'
for the front page, due to my if-statement (I hope).