Manipulating menu HTML

My site’s menu uses the built-in menu under Appearance >> Menus. I want to make a very simple change: I want to wrap each of my menu’s second-level ULs in a DIV.

What’s the simplest way to accomplish this?

Related posts

Leave a Reply

1 comment

  1. Use a custom walker. Extend the functions start_lvl() and end_lvl():

    class WPSE39005_Div_Walker extends Walker_Nav_Menu
    {
        /**
         * @see Walker::start_lvl()
         *
         * @param string $output Passed by reference. Used to append additional content.
         * @return void
         */
        public function start_lvl( &$output, $depth )
        {
            $output .= '<div><ul class="sub-menu">';
        }
    
        /**
         * @see Walker::end_lvl()
         *
         * @param string $output Passed by reference. Used to append additional content.
         * @return void
         */
        public function end_lvl( &$output, $depth )
        {
            $output .= '</ul></div>';
        }
    }
    

    Call it in your theme like that:

    <?php
    // If there is no menu assigned we show nothing.
    has_nav_menu( 'top-menu' )
    // Path to the file with the walker relative to theme’s root.
    and locate_template( 'php/class.WPSE39005_Div_Walker.php', TRUE, TRUE )
    and wp_nav_menu(
        array (
        'menu'       => 'top-menu'
    ,   'walker'     => new WPSE39005_Div_Walker
        )
    );
    ?>