Custom menus in WordPress

Wednesday, June 11th, 2014

Whenever I build a WordPress theme I’ll always include a couple of custom menus. I normally set these up as the main navigation and for any legal links which are meant to appear in the footer.

I find the addition of these menus means I touch the code far less once the site has launched. As an administrator of the site I can have total control over the links which appear within these menus via the dashboard.

This control is important for a couple of reasons.

  • The structure of the site will remain logical with the user’s needs catered for
  • The navigation will remain as per the intended design

Had the navigation been populated with say the use of wp_list_pages anyone with editor rights has the ability to change the navigation of your site by simply adding a new page. This is something you really want to avoid, particularly if your site is a community project where you could potentially have multiple people with all different kinds of knowledge and skills updating a live site, with no QA process.

Custom menus are really simple to set up. First you need to enable them within your theme and to do that you’ll need to edit your functions.php file found within your theme folder. Adding the following lines of php enables a new menu item under appearance titled Menus. As the appearance menu is only visible to administrators our navigation should be safe from changes without our knowledge.

The code above will only add one menu called ‘Main Navigation’ to the theme location called ‘primary-menu’. If you wish to have more then you can simply add them to the array, like so

Now the backend part has been sorted you can now add links to your menu(s) via the WordPress dashboard.

In order for the menus to appear in your site you need to tell your template to call them in. Firstly you need to locate the template which controls the area where you wish the menu to be displayed. Our main navigation will most likely be located in header.php template.

The outputted HTML will look something like this, with both the href attribute and text as per your instructions within the dashboard.

You’ll most probably want to add a containing class to the menu, if that is the case then you can change the code to this;

The class is added to the class main-navigation to the ul element like so;

you can also add multiple classes if you wish;

The output will look something like this.