ARIA Accessibile WordPress Menu
class {NAV_WALKER_NAME} extends Walker_Nav_Menu {
// add role menu to all wrapping menu lists
function start_lvl(&$output, $depth = 0, $args = array())
{
$output .= '<ul role="menu">';
}
function start_el(&$output, $object, $depth = 0, $args = array(), $current_object_id = 0)
{
// add role none to list items
$output .= '<li role="none" class="' . implode(' ', $object->classes) . '">';
// if this is a link (has url, isn't a #), add role menuitem
if ($object->url && $object->url != '#') {
$output .= '<a role="menuitem" href="' . $object->url .'">';
} else {
// this assumes # is only used for menu titles
// switch this from an anchor to a button (?), add aria roles to signify this contains a menu
$output .= '<button aria-label="Open ' . $object->title . ' sub menu" aria-haspopup="true" aria-expanded="false">';
}
$output .= $object->title;
if ($object->url && $object->url != '#') {
$output .= '</a>';
} else {
$output .= '</button>';
}
}
}
// update menu output, usually resources/partials/header.php
{!! wp_nav_menu([
'theme_location' => '{NAV_LOCATION}',
'walker' => new {NAV_WALKER_NAME}(),
'menu_class' => $nav_classes,
'items_wrap' => '<ul id="%1$s" class="%2$s" role="menubar">%3$s</ul>' // append role menubar to the parent wrapping list
]) !!}