0

I want to wrap each sub-menu ul and the tag just before it with a div.

I can create the opening tag using the 'before' attribute of wP-nav_menu like this:

wp_nav_menu(array(
    'before' => '<div class="child-wrap">'
));

The div then needs to close after the link but also after the submenu so the output is:

<ul>
    <li>
        <div class="child-wrap">
            <a href="...">Menu Item</a>
        </div>
    </li>
    <li>
        <div class="child-wrap">
            <a href="...">Menu Item</a>
            <ul class="sub-menu">
              ....
            </ul>
        </div>
    </li>
</ul>

I know I can use a Walker but I really don't understand how it works (inside the walker class) so any help would be appreciated...

  • And what output would you like to get exactly? – Krzysiek Dróżdż Apr 22 '14 at 16:17
  • @KrzysiekDróżdż, I've shown the output i'd like to get in the question. Please read more carefully. – Ralphonz Apr 22 '14 at 16:45
1

Ifigured it out myself, thanks to reading this: http://code.tutsplus.com/tutorials/understanding-the-walker-class--wp-25401

I created a custom walker:

class Child_Wrap extends Walker_Nav_Menu
{
    function end_el(&$output, $item, $depth)
    {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</div></li>\n";
    }
}

And used wp_nav_menu:

function main_nav() {
wp_nav_menu(array(
    'before' => '<div class="child-wrap">',       // before the menu
    'walker' => new Child_Wrap 
));
}
0

http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_items

You can use this example to get started:

    // Get the nav menu based on $menu_name (same as 'theme_location' or 'menu' arg to wp_nav_menu)
// This code based on wp_nav_menu's code to get Menu ID from menu slug

$menu_name = 'custom_menu_slug';

if ( ( $locations = get_nav_menu_locations() ) && isset( $locations[ $menu_name ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );

$menu_items = wp_get_nav_menu_items($menu->term_id);

$menu_list = '<ul id="menu-' . $menu_name . '">';

foreach ( (array) $menu_items as $key => $menu_item ) {
    $title = $menu_item->title;
    $url = $menu_item->url;
    $menu_list .= '<li><a href="' . $url . '">' . $title . '</a></li>';
}
$menu_list .= '</ul>';
} else {
$menu_list = '<ul><li>Menu "' . $menu_name . '" not defined.</li></ul>';
}
// $menu_list now ready to output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.