Add custom classes to anchor in wp_nav_menu

I want to add a custom class to anchors in wp_nav_menu outputs.

Default for example is:

<li id="menu-item" class="menu-item menu-item-type-custom">
<a href="">example</a>

I want this :

<li id="menu-item" class="menu-item menu-item-type-custom ">
<a href="" class="class">example</a>

Solutions Collecting From Web of "Add custom classes to anchor in wp_nav_menu"

You can add classes natively via interface in admin. Open Screen Options (top right of the screen) and check CSS Classes. I don’t remember if class applies to link itself, but you can always target link inside container with CSS (.class a).

You can do this with the nav_menu_link_atrributes filter.

add_filter( 'nav_menu_link_attributes', 'wpse156165_menu_add_class', 10, 3 );

function wpse156165_menu_add_class( $atts, $item, $args ) {
    $class = 'class'; // or something based on $item
    $atts['class'] = $class;
    return $atts;