Classic widget menus have a builtin aria-label, which either uses the widget’s title or a generic “Menu”. This can be improved.

Since the menu itself has already a name – because it has to be added when creating the menu in Appearance > Menus – why not using this instead of a generic one? Also, when adding a title to the widget menu, this title is always being displayed in the frontend, which is not necessarily desired.

Thus, I looked into how to adjust the code to always prefer the navigation menu name, if available. Since I didn’t want to parse the whole widget markup code (which even isn’t that easy to achieve), I stumbled upon the widget_nav_menu_args filter, which allows to filter the attributes passed to the menu widget. It also has the menu data already as part of the attributes, so setting its container_aria_label can be achieved within a few lines of code:

/**
 * Set the aria-label of a widget menu to the actual menu name.
 * 
 * @param	mixed[]	$nav_menu_args Widget menu arguments
 * @return	mixed[] Updated widget menu arguments
 */
function epiphyt_set_widget_aria_label( array $nav_menu_args ): array {
	if ( ! empty( $nav_menu_args['menu']->name ) ) {
		$nav_menu_args['container_aria_label'] = $nav_menu_args['menu']->name;
	}
	
	return $nav_menu_args;
}

\add_filter( 'widget_nav_menu_args', 'epiphyt_set_widget_aria_label' );
Code language: PHP (php)

Whenever the menu has a name set, it is used as ARIA label for the widget. If you want, you can adjust the code to use it only as fallback if you want to have a higher priority for the widget title, of course.

Reposts

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn more about webmentions)