Simple Navigation Walker – Wrapper-class around first sub-menu

To be honest, I don’t really know why my solution works, but it does 😂

I based my snippet on this solution and tweaked the output to my needs:
Custom nav walker with different output depending on depth

class sublevel_wrapper extends Walker_Nav_Menu {
    // add classes to ul sub-menus
    function start_lvl( &$output, $depth = 0, $args = array() ) {
        // depth dependent classes
        $indent = ( $depth > 0  ? str_repeat( "\t", $depth ) : '' ); // code indent
        $display_depth = ( $depth + 1); // because it counts the first submenu as 0
        $classes = array(
            'sub-menu',
            'menu-depth-' . $display_depth
        );
        $class_names = implode( ' ', $classes );

        // build html
        if ($display_depth == 1) {
            $output .= "\n" . $indent . '<div class="sub-menu__wrapper"><ul class="' . $class_names . '">' . "\n";
        } else {
            $output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n";
        }
    }
}

Compared to my first snippet he leaves out the end_lvl-function completely and for whatever reason it worked. I also liked how he adds the $display_depth-variable.

Leave a Comment