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" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">example</a>
</li>

I want this :

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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

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

Method 4

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x