Just wondering if someone can please help me with the code to add to an existing menu walker in a WordPress 4.7.4 nav menu called “main” to add a span around the page title in the A link to all top level items.

I would like the (simplified) html to look like so:

<ul>
    <li><a href="#" title="Page 1"><span>Page 1</span></a></li>
    <li><a href="#" title="Page 2"><span>Page 2</span></a><div class="drop">
        <ul>
            <li><a href="#" title="Sub Page 2.1">Sub Page 2.1</a></li>
            <li><a href="#" title="Sub Page 2.2">Sub Page 2.2</a></li>
            <li><a href="#" title="Sub Page 2.3">Sub Page 2.3</a></li>
            <li><a href="#" title="Sub Page 2.4">Sub Page 2.4</a></li>
        </ul>
    </div></li>
    <li><a href="#" title="Page 3"><span>Page 3</span></a></li>
    <li><a href="#" title="Page 4"><span>Page 4</span></a><div class="drop">
        <ul>
            <li><a href="#" title="Sub Page 4.1">Sub Page 4.1</a></li>
            <li><a href="#" title="Sub Page 4.2">Sub Page 4.2</a></li>
        </ul>
    </div></li>
    <li><a href="#" title="Page 5"><span>Page 5</span></a></li>
    <li><a href="#" title="Page 6"><span>Page 6</span></a></li>
    <li><a href="#" title="Page 7"><span>Page 7</span></a></li>
</ul>

The walker in my functions.php file currently has code in it to add a wrapper div around sub menu items for a drop down menu. This works great and is shown below:

class main_menu_walker extends Walker_Nav_Menu
{
    function start_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("t", $depth);
        $output .= "n$indent<div class="drop"><ul>n";
    }
    function end_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("t", $depth);
        $output .= "$indent</ul></div>n";
    }
}

Link_before and link_after attributes in the menu call don’t seem appropriate because they add spans to all menu items including sub pages.

I found some functions.php code for adding a span around top level items but this adds spans to the top level items of all WP menus, not just the menu called “main”. This code is show below:

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;
});

Can the above code work inside a menu walker for the one menu called main? If so, how do I implement that? Or is new code required for the menu walker? If so, any ideas?

Thanks in advance for any help.

Read more here: menu walker – add span around page title in the A link of top level items in a WordPress nav menu


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: