wordpresswordpress-themingwp-nav-menu-item

Add extra div to WordPress nav items


Whats the most simple way to change my wp-menu generated output from

<ul class="primary-menu">
<li class="menu-item">
    <a href="">nav link</a>
    <ul class="sub-menu"></ul>
</li>
</ul>

to

<ul class="primary-menu">
<li class="menu-item">
    <div class="alignme">
        <button></button><a href=""></a><button></button>
    </div>
    <ul class="sub-menu"></ul>
</li>
</ul>

?

I need this kind of "helper div" because I have to align the three elements in a certain way and independent from possible additional content (eg submenu) inside the li.

I am using default wp_nav_menu() and as a first-time theme builder I have no idea where to find the "setup" of the menu. Any idea where I should have a closer look?


Solution

  • add walker class in wp_nav_menu "new Add_Div_Walker". check my below code.

    $menu = array(
        'theme_location'  => 'primary',
        'items_wrap'      => '<ul id="%1$s" class="%2$s">%3$s</ul>',
        'walker'          => new Add_Div_Walker
    );
    wp_nav_menu( $menu );
    
    // add this below code in your functions.php file.
    class Add_Div_Walker extends Walker_Nav_Menu {
        function start_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat("\t", $depth);
            $output .= "\n$indent<div class='alignme'>
                <button></button><a href=''></a><button></button>
            </div><ul class='submenu'>\n";
        }
        function end_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat("\t", $depth);
            $output .= "$indent</ul>\n";
        }
    }