I'm creating a menu that will have sub-menu > sub-menu > sub-menu. The styling is really involved so ideally I could rename the class name "sub-menu" based off what level of sub-menu it is or at least add a class (ie 1st sub-menu add .top-sub-menu, 2nd sub-menu add .second-level-sub-menu, 3rd sub-menu add .third-level-sub-menu).
I attached the html of what I've got going on if that helps. Any help is much appreciated. Thanks!
I'm creating a menu that will have sub-menu > sub-menu > sub-menu. The styling is really involved so ideally I could rename the class name "sub-menu" based off what level of sub-menu it is or at least add a class (ie 1st sub-menu add .top-sub-menu, 2nd sub-menu add .second-level-sub-menu, 3rd sub-menu add .third-level-sub-menu).
I attached the html of what I've got going on if that helps. Any help is much appreciated. Thanks!
I was able to work this out by using a hook that I grabbed from Artemiy Egorov's answer on this post https://stackoverflow.com/questions/5034826/wp-nav-menu-change-sub-menu-class-name so I figured I'd share in case someone else needs it too:
add_filter( 'nav_menu_submenu_css_class', 'rename_sub_menus', 10, 3 );
function rename_sub_menus( $classes, $args, $depth ){
foreach ( $classes as $key => $class ) {
if ( $class == 'sub-menu' && $depth == 0) {
$classes[ $key ] = 'first-level-sub-menu';
} else if ( $class == 'sub-menu' && $depth == 1) {
$classes[ $key ] = 'second-level-sub-menu';
} else if ( $class == 'sub-menu' && $depth == 2) {
$classes[ $key ] = 'third-level-sub-menu';
}
}
return $classes;
}
$depth
of the menu items which is exactly what you're asking about, anybody with basic beginner level PHP skills can use anif
statement to check its value and return a different class. The answer by vralle even uses the depth to add a class with the depth value and does it in a filter that can be added to any menu. Note that any answer you got here would not be a copy paste solution – Tom J Nowell ♦ Commented Apr 25, 2023 at 16:28