10

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>

4 Answers 4

27

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;
}
3
  • How would I accommodate multiple different atts within the anchor? ie. not just adding classes but also adding aria-expanded="false"? Commented Jul 18, 2018 at 11:48
  • 1
    Like in the third line of the function.
    – cjbj
    Commented Jul 18, 2018 at 11:52
  • I have a better solution stackoverflow.com/a/67859550/9207553 Commented Jun 6, 2021 at 13:19
4

I have solution to add class to anchor tag.

1: Step: add this in functions.php

function add_additional_class_on_a($classes, $item, $args)
{
    if (isset($args->add_a_class)) {
        $classes['class'] = $args->add_a_class;
    }
    return $classes;
}

add_filter('nav_menu_link_attributes', 'add_additional_class_on_a', 1, 3);

2: Then use it like this in your theme

<?php
        // Show Menu here
        wp_nav_menu(array(
            'theme_location' => 'my-footer-menu',
            'menu_class'      => 'footer-top list-unstyled',
            'add_a_class'     => 'box-link text-dark',
        ));
?>
2

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

2
  • 1
    Admin allows you to apply CSS only to <li> elements, not <a> elements as asker desires.
    – Fusion
    Commented Feb 14, 2019 at 2:27
  • This does not add a class to the anchor tag, only the li containing it.
    – Lisa
    Commented Jun 26, 2023 at 18:06
0
add_filter( 'nav_menu_link_attributes', 'wpse156165_menu_add_class', 10, 3 );

function wpse156165_menu_add_class( $classes, $item, $args ) {
    if(isset($args->add_link_class)) {
        $classes['class'] = $args->add_link_class;
    }
    return $classes;
}

Now you can use add_link_class as an array in menus.

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