Custome Menubar Support in wordpress

Woocoders
Woocoders
2nd September 2020

The navigation menu feature, introduced in WordPress 3.0, allows for the intuitive creation and maintaining of navigation menus in themes.At the very least, a standard theme will need a main navigation menu, perhaps in the header and a secondary navigation menu in the footer. To do this, we will register those two menus “Main Menu” and “Secondary Menu”While this isn’t a particularly new feature, its still nice to wrap it in an if function_exists() just in case the user is stuck in a pre 3.0 installation:In the functions.php file, include the following:

if ( function_exists( 'register_nav_menus' ) ) {
 register_nav_menus(
  array(
    'main_menu' => __( 'Main Menu', 'cake' ),
    'secondary_menu' => __( 'Secondary Menu', 'cake' ),
  )
 );
}

Now that the Menus are registered, we need to tell the theme where to output them. We’d like the Main Menu to appear in our header. So, in our header.php file, we include the following code:

<?php if ( has_nav_menu( 'main_menu' ) ) { ?>
 <?php $defaults = array(
   'theme_location'  => 'main_menu',
   'menu'            => '', 
   'container'       => false, 
   'echo'            => true,
   'fallback_cb'     => false,
   'items_wrap'      => '<ul id="%1$s"> %3$s</ul>',
   'depth'           => 0 );
   wp_nav_menu( $defaults );
 ?>
<?php } else { ?>
 <ul>
   <?php wp_list_pages('title_li='); ?>
 </ul>
<?php } ?>

First, we check to see if we have a menu called ‘main_menu’ defined and if we do, we insert its contents here, otherwise we fallback to the default wp_list_pages() which we can further customize to display the links as we need.If you’d like even further customization of the menu, see the WordPress codex page on wp_nav_menu() function.We want the secondary menu to appear in the footer, so we open up the footer.php and include the following code:

<?php if ( has_nav_menu( 'secondary_menu' ) ) { ?>
 <?php $defaults = array(
   'theme_location'  => 'secondary_menu',
   'menu'            => '', 
   'container'       => false, 
   'echo'            => true,
   'fallback_cb'     => false,
   'items_wrap'      => '<ul id="%1$s"> %3$s</ul>',
   'depth'           => 0 );
   wp_nav_menu( $defaults );
 ?>
<?php } else { ?>
 <ul>
   <?php wp_list_pages('title_li='); ?>
 </ul>
<?php } ?>

Share this post: