8

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

24

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

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

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',
        ));
?>
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.

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.