Adding or Registering menus to a WordPress website has frequently been a challenge which is why I believe it deserves its own post as we learn about register_nav_menus() then adding those Navigation Menus to our theme.

At first glance the process appears simple, add a function to functions.php to “register” the menus.

functions.php

// Register Header and Footer Menus
function scratch_jd_theme_setup() {
	register_nav_menus(
		array( 
			'header-menu' => __( 'Header', 'scratch-jd' ),
			'footer-menu' => __( 'Footer', 'scratch-jd' ),
		)
	);
}
add_action( 'after_setup_theme', 'scratch_jd_theme_setup' );

Next use wp_nav_menu() in our template (or templates) to display the menu.

header.php

wp_nav_menu( array( 'theme_location' => 'footer-menu' ) );

footer.php

wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); 

These code samples above are in addition to the files used in Building a Basic WordPress Theme.

If you’d like to glance the complete files visit this snippet.

Where registering menus gets gets tricky is if there is a mismatch between the registration and the template file that hooks it into the page. If wp_nav_menu() doesn’t find the desired menu WordPress displays a fallback… In this case the only page on my website Sample Page. Since this isn’t expressed as an error we’re not really sure what’s wrong here. Only that its not the expected result.

These aren’t the the menus you are looking for

However, if things work outour assigned menu will display properly.

Assigning our menu to Header and Footer Display locations
The assigned menus we’re expecting

Template Tags

Until thiss point our theme hasn’t generated any html beyond a paragraph tag in the Welcome post.

However, wp_nav_menu() is one of many Template Tags that WordPress provides by to help designers and developers customize our website.

developer tools inspection of a WordPress menu.
Not just unordered lists and list items are inserted but custom classes as well.

In the image above which inspects the menus list links you’ll note a class of current_page_item which could be used to differentiate the current page as it appears in the menu. All without custom JavaScript. A feature that will be handy later when we plan our our design and accessibility features.


CC0
To the extent possible under law, Joseph Dickson has waived all copyright and related or neighboring rights to Building a WordPress Theme From Scratch. This work is published from: United States.