Adding a class to Wordpress sub menus

Sometimes it's a nice visual cue to differentiate Wordpress menu items with children from those without.

Adding a class to WordPress sub menus
Shawn Wernig
June 19, 2024
by Shawn Wernig

This function below will add the class has-sub-menu to every Wordpress menu item with a submenu, and allow you to style it as you see fit!

This function below will add the class has-sub-menu to every WordPress menu item with a submenu, and allow you to style it as you see fit! Place this function in your functions.php file:

function eps_add_submenu_class( $menu_items, $args ) {
    $last_top = 0;
    foreach ( $menu_items as $key => $obj ) {

        if ( $obj->menu_item_parent != 0 && $last_parent == $obj->menu_item_parent ) {
           $menu_items[$last_top]->classes['has-sub-menu'] = 'has-sub-menu';
        }
        $last_top = $key;
        $last_parent = $obj->ID;
    }
    return $menu_items;
}
add_filter( 'wp_nav_menu_objects', 'eps_add_submenu_class', 10, 2 );
Eggplant Studios - Custom Website Design and Development
Creating custom web solutions and happy clients since 2002
COPYRIGHT ©
2024
Eggplant Studios
- ALL RIGHTS RESERVED
LOGIN