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="http://example.com">example</a>
</li>

I want this :

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

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;
}