How to add header before ul using wp_nav_menu?

I need to add a title to my menu wp_nav_menu creates ... 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>

It seems strange to me that this is not enabled by default: s

+5
source share
4 answers

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>'
  )
);
+6
source

This seems like a slightly broken option, I followed the manual on wordpress codex and related recommended manual, and each time item_wrap did nothing, my menu source code was

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

What didn’t work, and after a lot of hair pulling, I switched to this

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

What happens is both basically identical, so if it doesn't work the first time, don't give up, throw it back and keep trying!

+2

There is usually a way to do this without editing the kernel. I copied the wp_nav_menu () function codes and modified them a bit.

  // 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 the WordPress Codex , you should never hack the core of WordPress because:

Do not hack core

0
source

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>';
-3
source

All Articles