Add your own CSS class to the links in a menu, such as a "nav-link" class your design system or framework expects.
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 );
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.
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'].
primary to your theme’s menu location. Find location names under Appearance → Menus → Manage Locations.View your page source and find the primary menu. Each <a> should include class="nav-link".