WordPress nav walker to count sub-menus

In a WordPress menu, I need to add a class to the parent <li> when it has 3 levels (when the parent’s sub-menu also has sub-menu). In other words:

<ul>
    <li>Parent
        <ul class="sub-menu">
            <li>Sublink1</li>
            <li>Sublink2</li>
        </ul>
    </li>
    <li>Parent</li>
    <li class="mega">Parent <!-- add class here b/c it has 3 levels -->
        <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 sure I need to use a Walker to achieve this, but I haven’t been able to find an example of one that does something like this. Thank you!

Related posts