WordPress – How to add a navigation menu to your theme

In this tutorial I will show you, how easy it is to implement a custom navigation menu in WordPress, so as you are able to dynamically manage links from within the WordPress administration.

There are needed only 3 code interventions from your side:

  1. make your theme support menus
  2. to register a menu within our functions.php file
  3. to place the menu into our desired location

1. Make your theme support menus

If you’ve been working with WordPress for some time, you know that the functions, like for example widgets, html5 search form, featured images…etc, need to be registered from within via add_theme_support() function.

The navigational menus are not an exception and you can simply add theme support for the nav menus just like so:

add_action('after_setup_theme', function () {
    add_theme_support('menus');
});

2. Register a menu within our functions.php file

The next step is to actually register a navigation menu, so as it is possible to add links from within a WordPress administration. You accomplish that via register_nav_menus() function. This function can not be called just from any place, but only from within an action after_setup_theme and you can use the following code to do just that:

add_action( 'after_setup_theme', function () {
    register_nav_menus( array(
        'primary' => 'Primary Navigation',
    ));
});

As you can see, the function register_nav_menus() accepts an array and it allows you to register multitude of navigational menus.

The structure is very simple. key => value. key is important, since you will be displaying the menu by that key and value will be as an identifier for the menu inside WordPress administration.

3. Place the menu into the desired location

If you want your menu to be in header.php, footer.php, sidebar.php.. it does not matter. The code is still the same and it is as follows:

wp_nav_menu( array( 'theme_location' => 'primary' ) );

The only required parameter is theme_location and it is the key value used from register_nav_menu() function.

The function wp_nav_menu() got a whole bunch of parameters, which will allow you to customize menu in the terms of adding custom attributes (id, class…), custom html structure and so on.

The last step

The last step is obviously to navigate into the WordPress administration -> Appearance -> Menus and simply create the menu.

Wrapping up

In this quick guide I walked you through how to create a custom menu for your WordPress theme so as you are able to manage links via WordPress administration.

A video tutorial will be available shortly.

Until then,

Yours in coding.

Ivan

Sources:

Similar articles:

Leave a comment

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