PHP Code to add 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 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 a 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. 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 a ID for which your menu location is allocated, in this case in header “Primary Menu“. It can also called in 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',
  ) );
?>
  •  wp_nav_menu is 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

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

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

Wordpress theme without Menu option

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

Wordpress theme without Menu option WordPress theme with Menu option

What custom code do you need in WordPress? Comment below your opinion and suggestions also.

Leave a comment

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