Add Menu Parent Class

February 21, 2014 in Snippets

If you want to detect which menu item has children, this snippet add a class to a menu item if it has children items.

function add_menu_parent_class( $items ) {
    $parents = array();
    foreach ( $items as $item ) {
        if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
            $parents[] = $item->menu_item_parent;
        }
    }
 
    foreach ( $items as $item ) {
        if ( in_array( $item->ID, $parents ) ) {
            $item->classes[] = 'menu-parent-item';
        }
    }
 
    return $items;    
}
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );

Note: Since WordPress 3.7 classes .menu-item-has-children for wp_nav_menu , .page_item_has_children for wp_page_menu has been added to menus to indicate that an item has sub-items (http://codex.wordpress.org/Function_Reference/wp_nav_menu#How_to_add_a_parent_class_for_menu_item).