Walker nav remove submenu ul from a certain depth

I want to remove sub-menu ul and .menu-item-has-children class when the menu depth is superior or egal to 2.

So, I only want a menu with 3 sub-menu at maximum. Other item children will still displayed in the menu but not in a sub menu.

With wp_nav_menu(‘depth’ => 3) it don’t append all items. So, I think I need to use a custom walker nav.

I don’t know how to do it with start_lvl. What is the way to count depth and to remove ul and classes…

My aim is to change this menu:

  • menu-item-has-children
    • menu-item-1
    • menu-item-2
    • menu-item-has-children
      • menu-item-3
      • menu-item-4
      • menu-item-has-children
        • menu-item-5
        • menu-item-6

to this menu :

  • menu-item-has-children
    • menu-item-1
    • menu-item-2
    • menu-item-has-children
      • menu-item-3
      • menu-item-4
      • menu-item-has-children
      • menu-item-5
      • menu-item-6

And the unwanted behavior provides by wp_nav_menu(‘depth’ => 3) option in wordpress

  • menu-item-has-children
    • menu-item-1
    • menu-item-2
    • menu-item-has-children
      • menu-item-3
      • menu-item-4
      • menu-item-has-children

I’ve tried with this:

function start_lvl(&$output, $depth) { 
    if($depth >= 2) {
        $output .=  '';
    } else {
        $output .= "<ul class='sub-menu'>";
    }
}

It near works, but it create a problem with ul inside my navmenu.

Solutions Collecting From Web of "Walker nav remove submenu ul from a certain depth"

At first glance, and without testing anything, the code you’ve got should work but I expect that you have a number of spurious </ul> in your markup. You need to do nearly the same thing for the end_lvl method.

function end_lvl(&$output, $depth) { 
    if($depth >= 2) {
        $output .=  '';
    } else {
        $output .= "</ul>";
    }
}

I don’t know if that is the problem with your megamenu or not.