How do I Enable Navigation Menu in WordPress

PHP Code to register a header menu to custom WordPress theme

Open functions.php file in your theme and add the following PHP code snippet. If function.php does not exist, create one within the theme folder and add this snippet.

/** 
 * Include primary navigation menu
 */
function themename_nav_init() {
  register_nav_menus( array(
    'menu-1' => 'Primary Menu',
  ) );
}
add_action( 'init', 'themename_nav_init' );
  • themename_nav_init()is an action hook to initiate a call to WordPress function to let you create the menus. Replace “themename_nav_init” with any name suitable for you. But, make sure you use the same name in add_action function.
  • register_nav_menus This function automatically registers custom menu support with options in WordPress. The array parameters passed will help to create location and description. Read more info here on WordPress codex register_nav_menu.

NOTE :

register_nav_menus() allows you to register multiple location . whereas, register_nav_menu() allow you register single location.

  • menu-1” is an ID for which your menu location is allocated, in this case in header “Primary Menu“. It can also be called in the footer or sidebar.
  • add_action( 'init', 'themename_nav_init' ); this will trigger the function on page initialization, referred by “init”.

Open your header.php file and add the following snippet, where you want the menu to appear in your theme.

<?php
  wp_nav_menu( array(
       'theme_location' => 'menu-1',
       'menu_id'        => 'primary-menu',
       'depth' => 0,
       'container_class' => 'nav navbar',
  ) );
?>
  • wp_nav_menu is a WordPress function to display the navigation menu.
  • theme_location location at which the menu to be displayed. Works when you register with register_nav_menu.
  • menu_id the ID that is applied to the ul element which forms the menu.
  • depth is used to create nested menus.
  • container_class is the class name used for wrapping the menu container.

Along with these, there are a lot of optimization options to customize. Read more on wordpress codex wp_nav_menu

As you can see in the image below, under the Appearance tab, we do NOT have a Menu option enabled.

Register Menus in WordPress
WordPress dashboard before enabling menu option

After adding the register_nav_menu function we can now see that WordPress will provide a menu option to add menu items.

WordPress dashboard after enabling menu option

Let us know if this was useful or has there been any change. Cheers!. Please share, comment and subscribe.

Shares

Recommended Articles

Leave a Reply

Pin It on Pinterest

Shares