Remove sub-menu span in wp_nav_menu

I have a piece of HTML menu which I want to display in WordPress with wp_nav_menu.

The HTML

Read More
<nav id="navigation" class="ddsmoothmenu">
<ul id="main-menu">
    <li><a href="index.html" class="current"><span>Home</span></a>
        <ul>
            <li><a href="index-2.html">Home Alternate 2</a></li>
            <li><a href="index-3.html">Home Alternate 3</a></li>
            <li><a href="index-4.html">Home Alternate 4</a></li>
            <li><a href="index-5.html">Home Alternate 5</a></li>
            <li><a href="index-6.html">Home Alternate 6</a></li>
        </ul>
    </li>
 </ul>

I am adding the following in my WordPress header.php file to display the nav menu

$defaults = array(
               'theme_location'  => 'primary',
               'menu'            => 'Primary Menu',
               'container'       => '',
               'container_class' => '',
               'container_id'    => '',
               'menu_class'      => 'menu',
               'menu_id'         => '',
               'echo'            => true,
               'fallback_cb'     => 'wp_page_menu',
               'before'          => '',
               'after'           => '',
               'link_before'     => '<span>',
               'link_after'      => '</span>',
               'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
               'depth'           => 0,
               'walker'          => ''
             );
wp_nav_menu($defaults);

However the output is adding the tags also in the second level of the menu items as

<nav id="navigation" class="ddsmoothmenu">
<ul id="main-menu">
    <li><a href="index.html" class="current"><span>Home</span></a>
        <ul>
            <li><a href="index-2.html"><span>Home Alternate 2</span></a></li>
            <li><a href="index-3.html"><span>Home Alternate 3</span></a></li>
            <li><a href="index-4.html"><span>Home Alternate 4</span></a></li>
            <li><a href="index-5.html"><span>Home Alternate 5</span></a></li>
            <li><a href="index-6.html"><span>Home Alternate 6</span></a></li>
        </ul>
    </li>
 </ul>

Is there a way to add the span only for the top level menu item or remove the spans from the second level items?

Related posts

Leave a Reply

3 comments

  1. add_filter( 'wp_nav_menu_objects', function( $items ) {
          foreach ( $items as $item ) {
            if (!$item->menu_item_parent) {
               $item->title = '<span>' . $item->title . '</span>';
            }
        }
        return $items;
    });
    
  2. Ok, While walker seems to be one good way of getting this done, it seems to be pretty elaborate with many lines of codes. I just found out that the easiest way to remove the span for the sub-menu items is with jQuery. WordPress automatically adds the sub-menu class to the child ul and hence what worked for me was

    $('ul.sub-menu li a span').contents().unwrap();
    

    Hope this helps.