How to Register and Add Navigation Menus in WordPress

If you’re developing a custom WordPress theme or using a theme where you want to add a new navigation menu, then this post is for you. WordPress allows you to create numerous navigation menus. There’s no limits.

With little code in your functions.php file, you can register custom menus and show them anywhere in your site.

How to Register Menus in WordPress

First let’s see how we can register menus in WordPress. Check out the code below.

Here, we used register_nav_menu function to register our menu in WordPress. This function requires two parameters. These are –

  • $location – This is the menu location identifier. This is what WordPress will understand to execute your code properly.
  • $description – This is the menu description – to identify the menu in Dashboard. This will appear in admin Dashboards’ menu page.

Then we used the ‘init’ action hook to add this menu to our WordPress theme.

You can name your menu anything you like. But make sure your location identifier contains no spaces and capital letters.

You can also register multiple menus at a time.

Notice, we used register_nav_menus function instead of register_nav_menu. This function is used when we want to register multiple menus at a time.

This function requires an associative array as a parameter where $location is used as the key and $description is the value.

If you’re wondering why, __() – two underscores are used with the description, that’s for translation or localization issues.

How to Show Navigation Menu in WordPress

Now, let’s see how we can show registered menu in our WordPress site.

WordPress provides wp_nav_menu function to show any navigation menu anywhere in your site. You can add it in your header.php if you want to add your navigation menu to the header. You can add it in your footer.php if you want to add the menu in your footer file.

wp_nav_menu function accepts an array as parameters. You can pass various information regarding the menu using this array. Here,

  • ‘theme-location’ is telling WordPress the location of menu which we registered before.
  • ‘depth’ is used if you are creating multilevel menus or nested menu.
  • ‘container_class’ is the class that is applied to the container.
  • ‘menu_class’ is the CSS class to be used for ul elements which form the menu.
  • ‘walker’ is an instance of a custom class which helps with the multilevel menus.

There are other arguments you can use here. These are – ‘menu’, ‘menu_id’, ‘container’, ‘container_id’, ‘fallback_cb’, ‘before’, ‘after’, ‘link_before’, ‘link_after’ etc. For more information on WordPress Navigation Menus click here.

I hope now you know – how to register and add navigation menu in WordPress. If you find this helpful, don’t forget to share this post with others.

Let me know through comments if you have any queries.

Click Here to Leave a Comment Below

Leave a Reply: