Remove ‘ul’ and ‘li’ tags from WordPress menus while retaining all the classes

Problem:
I need to output a WordPress nav menu as a series of anchors surrounded by spans, within one nav element. Manipulating the args passed to wp_nav_menu() function will allow the <ul> element to be removed, and passing the output through ‘striptags’ can remove the <li> elements, but I end up losing all the link ancestry classes.

Solution:
If a ‘Walker’ class is used, the output from wp_nav_menu() can be controlled totally. Here’s an example that removes the list elements, adds a span around each item link, and adds the possibility of a separator string between each menu item.

Add to your theme / header / etc:

<nav role="navigation">
 <?php
 $menuArgs = array(
 'container' => false,
 'items_wrap' => '%3$s',
 'separator' =>'|', //this is a custom arg I've added, not a 'core' one.
 'walker' => new nolist_walker()
 );
 wp_nav_menu($menuArgs);
 ?>
</nav>

Add to functions.php or a plugin:

class nolist_walker extends Walker_Nav_Menu {
 function start_el(&$output, $item, $depth, $args) {
  $classes = empty($item->classes) ? array () : (array) $item->classes;
  $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item));
  !empty ($class_names) && $class_names = 'class="'. esc_attr($class_names) . '"';
  !empty($args->separator) && ($item->menu_order > 1) && $output .= '<span class="menu-sep">'.$args->separator."</span>n";
  $output .= "<span id='menu-item-$item->ID' $class_names>";
  $attributes = '';
  !empty($item->attr_title) && $attributes .= ' title="' . esc_attr($item->attr_title) .'"';
  !empty($item->target) && $attributes .= ' target="' . esc_attr($item->target) .'"';
  !empty($item->xfn) && $attributes .= ' rel="' . esc_attr($item->xfn) .'"';
  !empty($item->url) && $attributes .= ' href="' . esc_attr($item->url) .'"';
  $title = apply_filters('the_title', $item->title, $item->ID);
  $item_output = $args->before."<a$attributes>".$args->link_before.$title.'</a>'.$args->link_after.$args->after;
  $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
 }
 function end_el(&$output, $item, $depth) {
  $output .= "</span>n";
 }
}

Hopefully that’s pretty clear. If you have any questions let me know in the comments and I’ll try and help. If I’ve made a dork mistake, let me know and I’ll correct it

🙂

Please let me know if this snippet was useful, just one click!
Nope, not helpful...Yep, more useful than not! - +1 thumb, 3 overall.
Loading...

Leave a Reply

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