How do I Add Navigation Menus?

Posted on: April 20, 2017 | Categories: Lesson | Tags: , , ! Course:

Now that you have your styles and scripts working, let’s register support for navigation menus. If you’ve used WordPress with built-in or third party themes, you’re probably familiar with creating menus in your site’s dashboard. When we create our theme from scratch, we have to register our menus using actions and identify the placement for each menu.

To start, we’ll register two menus in our functions.php file:

function register_jeffhow_menus() {
  register_nav_menus(
    array(
      'header-menu' => 'Header Menu' ,
      'footer-menu' => 'Footer Menu'
    )
  );
}
add_action( 'init', 'register_jeffhow_menus' );

The function used above registers both menus at once. The array values represent the “locations” for each menus. Since I’ll be placing one in the header and the other in the footer, I’ve named them accordingly. Now that we’ve registered these menus in the functions file, we need to identify their placement in our theme.

Add the following to your header.php file:

<nav>
  <?php wp_nav_menu( array( 'theme_location' => 'header-menu' ) ); ?>
</nav>

And to the footer.php file:

  <nav>
    <?php wp_nav_menu( array( 'theme_location' => 'footer-menu' ) ); ?>
  </nav>
</footer>

Make Some Menus and Preview

Now we should be able to create menus in our dashboard and assign them to the correct locations within our theme:

new menu in the dashboard
New menu in the dashboard

We should see our menus appear on our site:

Preview of menus
Preview of menus

References

Navigation Menus

Leave a Reply

Your email address will not be published. Required fields are marked *

*