[Tutorial #19] Adding WordPress Menu

[Tutorial #19] Adding WordPress Menu


From previous tutorials we created the first wordpress content, the home page. Now that we have content to, it’s time to add menus in our wordpress site.

Adding wordpress menus involves three steps:

  1. Set the code in header.php or footer.php to display menus.
  2. Register menus in functions.php.
  3. Setup menus in the admin panel.

You can change the sequence of #1 and #2. You have to complete both #1 and #2 in order to do #3.

Menu Three Steps

1. Display nav menu: wp_nav_menu

In wordpress we use the function wp_nav_menu in templates to display a menu. The code segments from header.php is as follows (you can find it on my Github page:

Here the function takes a PHP associative array as parameters, which is just a set of variables and their values. The first variable 'theme_location', tells wordpress to display the menu with name as 'primary' .

You have to register menus that correspond to the value of 'theme_location' to show them!

Other variables are to set the menu’s HTML tags and classes. You can review them in the header tutorial. For other available parameter variables see its Codex page.

2. Make a menu available in admin panel: register_nav_menu

In functions.php, search or create the function register_nav_menu as follows (Github location):

The function’s parameter associative array contains names of menus with their descriptions (see Codex for more detail). Here we have two menus 'primary' and 'footer'. Their descriptions reflect that the first one is the primary menu of my site ModernBlackHand, and the other is the footer menu.

3. Setup menu in admin panel

After #1 and #2 are set we can then go to admin panel and setup the menu’s content. The location is Appearance -> Menus:

WP menu page

Menu page. The red area contains available items. The right is the menu’s actual items.

Here pay attention to the following three sections:

  1. Select a menu to edit (right on top of the red and blue areas shown in above image). Be sure to click “select”!
  2. Available items (the red area).
  3. This menu’s items. You can drag an item from the “available item” on the left to the right.

If you want to remove an item, expand the item’s drop-down symbol and there is the red ‘remove’ clickable text.

WP menu item drop-down

Upper right is the triangle to expand/close item’s drop-down. At the center is the ‘remove’ clickable text.

Once you add the home page into the menu, be sure to click the “save” button.

Header Style Customization

WordPress comes with two styles for <navbar> tag: navbar-default and navbar-inverse. But most of the time you want to create your own looking navbars.

In this tutorial we described how we can generate custom CSS styles to change our navbar’s colors.