Adding a class to WordPress sub menus

Sometimes it’s a nice visual cue to differentiate WordPress menu items with children from those whithout. 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 );
fold-left fold-right
About the author

Shawn Wernig is a web designer and developer, working primarily with Wordpress based websites. His company, Eggplant Studios is a small studio serving big clients in British Columbia, Canada.

Leave a Reply