Add class to top level menu item if it has multiple child levels

I have a WP nav menu, and I need to add a class to any top-level <li> if that item has more than one level of child items (meaning, its child submenu has a submenu too). Like this:

<ul>
    <li>Parent
        <ul class="sub-menu">
            <li>Sublink1</li>
            <li>Sublink2</li>
        </ul>
    </li>
    <li>Parent</li>
    <li class="ADD-CLASS-HERE">Parent <!-- add class to this item -->
        <ul class="sub-menu">
            <li>Sublink1</li>
            <li>Sublink2</li>
            <li>Sublink3
                <ul class="sub-menu">
                    <li>Sublink1</li>
                    <li>Sublink2</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>Parent</li>
    <li>Parent</li>
    <li>Parent
        <ul class="sub-menu">
            <li>Sublink1</li>
            <li>Sublink2</li>
        </ul>
    </li>
</ul>

I’m assuming I need to use a Walker to achieve this. (I don’t want to manually add the class in the WP Menu settings.) I’ve tried working with some example walkers I found, but I haven’t been able to get the class added to the level 0 ancestor item. Thank you for any help!

1 Answer
1

Not sure, but maybe something like this will work? Add to the functions.php.
See explanation here.

//This function is responsible for adding "my-parent-item" class to parent menu item's
function add_menu_parent_class( $items ) {
$parents = array();
foreach ( $items as $item ) {
    //Check if the item is a parent 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 ) ) {
        //Add "menu-parent-item" class to parents
        $item->classes[] = 'my-parent-item';
    }
}

return $items;
}

//add_menu_parent_class to menu
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' ); 

So if you can use Jquery you can do it like this:

$('ul li.menu-parent-item:has(ul ul)').addClass('your class');

Leave a Comment