0

I know there is this nav_menu_css_class hook to add a custom class to the list items in the nav, but is there a similar hook to add a custom class to all link items in the nav? I want all my links in the nav to have this class:

<a class="nav-link" href="#whatever">Sample page</a>

1 Answer 1

1

Yes, there is, and the hook is nav_menu_link_attributes:

apply_filters( 'nav_menu_link_attributes', array $atts, WP_Post $item, stdClass $args, int $depth )

Filters the HTML attributes applied to a menu item’s anchor element.

For example, this adds the nav-link class to the <a> tag only if the theme location ($args->theme_location) is exactly my-location:

add_filter( 'nav_menu_link_attributes', 'my_nav_menu_link_attributes', 10, 3 );
function my_nav_menu_link_attributes( $atts, $item, $args ) {
    if ( 'my-location' === $args->theme_location ) {
        // Get existing classes, if any.
        $class = $atts['class'] ?? '';

        // Now add your custom class(es).
        $atts['class'] = "$class nav-link";
    }

    return $atts;
}
1
  • 1
    This is perfect. Thank you for the sample code.
    – hnnnng
    Jan 31 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.