5

I need to add a title to my menu, which is being built by wp_nav_menu...something like this:

<div class="container">
  <div class="title">My Menu Title</div>
  <ul class="menu">
    <li class="item"><a href="#">Item 1</a></li>
    <li class="item"><a href="#">Item 2</a></li>
    <li class="item"><a href="#">Item 3</a></li>
  </ul>
</div>

I find it strange that this isn't included by default :s

5 Answers 5

7

This should work for you!

wp_nav_menu(
  array(
    'items_wrap' => '<div class="title">Your menu title</div><ul class="%2$s">%3$s</ul>'
  )
);
0
2

This seems like a slightly broken option, I followed the guide on the wordpress codex, and a linked recommended guide, and every time, items_wrap did nothing at all, my original menu code was

<?php wp_nav_menu( array( 'theme_location' => 'primary','items_wrap' => '<ul id="%1$s" class="sf-menu %2$s">%3$s</ul>' ) ); ?>

Which didn't work and after much hair pulling, I changed to this

<?php wp_nav_menu( array( 'items_wrap' => '<ul class="sf-menu %2$s">%3$s</ul>' ) ); ?>

Which does, both are basically identical, so if it doesn't work first time don't give up, strip back and keep trying!

2

You can use the WordPress function wp_get_nav_menu_name to display the menu title where you want, based on the theme location.

For the primary menu for example, you can use :

<h3><?php echo wp_get_nav_menu_name( 'primary' ); ?></h3>

<?php wp_nav_menu([
    'theme_location'  => 'primary',
    // ...
]); ?>
0

Commonly there is a way to do it without editing core. I copied the wp_nav_menu() function codes and slightly modified to do it.

  // set menu arguments
  $args = array('theme_location' => 'primary_navigation');

  // if menu parameter set directly get menu object directly
  if (isset($args['menu']))
    $menu = wp_get_nav_menu_object( $args['menu'] );
  // otherwise get it from theme location
  elseif ( !isset($menu) && $args['theme_location'] && ( $locations = get_nav_menu_locations() ) && isset( $locations[ $args['theme_location'] ] ) )
    $menu = wp_get_nav_menu_object( $locations[ $args['theme_location'] ] );

  // if menu name exists, pass it into items_wrap
  if (isset($menu) && isset($menu->name))
    $args['items_wrap'] = '<h6>'. $menu->name .'</h6><ul class="%2$s">%3$s</ul>';
    wp_nav_menu($args);

According to WordPress Codex, you should never hack WordPress core, because:

Do not hack core

-3

Hack function wp_nav_menu() in /wp-includes/nav-menu-template.php add after line 270

$nav_menu = $items = '';

this line:

$nav_menu .='<h3>'.$menu->name.'</h3>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.