Site icon Hip-Hop Website Design and Development

Adding a unique ID to each sub-menu

I have the following menu via header.php:

<?php
wp_nav_menu(
    array(
        'container' => false,
        'theme_location' => 'primary',
        'items_wrap' => '<ul class="header__nav-items header__nav-items--primary">%3$s</ul>',
    )
);

For parent menu items with children, I’m replacing the <a> tags with a button (controlled by ACF). Here’s the function:

<?php
function edit_menu_item($item_output, $item) {
    if ( get_field( 'dropdown', $item) == 'yes' ) { 
        return '<button aria-expanded="false" aria-controls="aria-'.$item->object_id.'" class="header__button">'.$item->title.'</button>';
    }
    return $item_output;
}
add_filter('walker_nav_menu_start_el','edit_menu_item', 10, 2);

When the button is clicked, the aria-expanded attribute switches from false to true. The sub-menu is also revealed. This is controlled via JavaScript.

With the above functions, this is what’s produced on the front-end.

<ul class="header__nav-items">
    <li class="menu-item-has-children header__nav-item">
        <button aria-expanded="true" aria-controls="aria-1880" class="header__button">Food</button>
        <ul class="sub-menu header__sub-menu header__sub-menu--toggled">
            <li class="header__nav-item"><a href="/pizza" class="header__nav-anchor">Pizza</a></li>
            <li class="header__nav-item"><a href="/burgers" class="header__nav-anchor">Burgers</a></li>
            <li class="header__nav-item"><a href="/fries" class="header__nav-anchor">Fries</a></li>
        </ul>
    </li>
</ul>

The aria-controls attribute has a unique ID. This ID needs to match up to my sub-menu.

How would I add a unique ID to each sub-menu?