Theme & Front End PHP Beginner

Add a Class to Menu Links

Add your own CSS class to the links in a menu, such as a "nav-link" class your design system or framework expects.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 7 lines
add_filter( 'nav_menu_link_attributes', function ( array $atts, $item, $args ): array {
	// Only the menu in the "primary" location.
	if ( 'primary' === ( $args->theme_location ?? '' ) ) {
		$atts['class'] = trim( ( $atts['class'] ?? '' ) . ' nav-link' );
	}
	return $atts;
}, 10, 3 );

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.

WordPress puts its classes on the menu’s list items, not on the links inside them. CSS frameworks and many designs expect a class on the link itself. This snippet adds one.

How it works

The nav_menu_link_attributes filter runs for every link in every classic menu, with the link’s attributes, the menu item and the menu’s settings. The snippet checks the theme location so only the primary menu is affected, then adds nav-link to any classes already there.

You can set other attributes the same way, such as $atts['data-track'].

Things to watch

  • Change primary to your theme’s menu location. Find location names under Appearance → Menus → Manage Locations.
  • Block themes’ Navigation block doesn’t use this filter.

How to test it

View your page source and find the primary menu. Each &lt;a&gt; should include class="nav-link".

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