5

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>
9

You can do this with the nav_menu_link_attributes 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;
}
  • How would I accommodate multiple different atts within the anchor? ie. not just adding classes but also adding aria-expanded="false"? – Robert Andrews Jul 18 '18 at 11:48
  • 1
    Like in the third line of the function. – cjbj Jul 18 '18 at 11:52
3

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).

  • Admin allows you to apply CSS only to <li> elements, not <a> elements as asker desires. – Fusion Feb 14 at 2:27

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.