Accessibility PHP Beginner

Add ARIA Labels to WordPress Navigation Menus

Automatically add descriptive aria-label attributes to WordPress navigation menus based on their registered location, helping screen readers distinguish between multiple nav elements on the same page.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 22 lines
add_filter( 'wp_nav_menu_args', function ( array $args ): array {
	$labels = [
		'primary' => 'Main',
		'footer'  => 'Footer',
		'mobile'  => 'Mobile',
		'legal'   => 'Legal',
		'social'  => 'Social media',
	];

	$location = $args['theme_location'] ?? '';
	if ( ! isset( $labels[ $location ] ) ) {
		return $args;
	}

	// Wrap the menu in a <nav> and give it a name screen readers can announce.
	if ( empty( $args['container'] ) || 'div' === $args['container'] ) {
		$args['container'] = 'nav';
	}
	$args['container_aria_label'] = $labels[ $location ];

	return $args;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Most sites have several menus: main navigation, footer links, social icons, legal links. Screen reader users can jump between navigation regions, but if each one is just called “navigation” they can’t tell them apart. This snippet gives each menu its own name.

How it works

The wp_nav_menu_args filter runs before every menu is printed. For theme locations in the list, the snippet makes sure the menu is wrapped in a <nav> element and sets container_aria_label, a wp_nav_menu() argument WordPress has supported since version 5.5. WordPress then prints aria-label="Footer" on the container.

The previous version set an argument called container_attrs, which wp_nav_menu() doesn’t support, so no labels were ever added.

Choosing labels

Keep them short and leave out the word “navigation”: screen readers already announce the region as navigation, so “Footer” is read as “Footer navigation”. Change the location keys to match the ones your theme registers; you’ll find them under Appearance → Menus → Manage Locations.

Things to watch

This only affects classic menus printed with wp_nav_menu(). In block themes, select the Navigation block and set its label in the block’s Advanced settings. Page builders like Bricks have their own menu elements with an ARIA label setting.

How to test it

View the source and find your footer menu. Its container should be <nav aria-label="Footer">. With a screen reader, the landmarks list should show each menu by name.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only