Add class to anchors in WordPress Menus
Asked Answered
T

4

16

I'm trying to add the standard Bootstrap nav-link class to the anchors rendered by the WordPress menu.

  1. I can pass variables to the wp_nav_menu() which applies a class to the menu (and remove the containing):

    <?php wp_nav_menu(array(
        'theme_location' => 'header-menu',
        'menu_class' => 'navbar-nav',
        'container' => 'false'
    ) );
    ?>
    
  2. I then use the WordPress Appearances > Menu UI to apply nav-item class to <li> tags.

How do I apply a class to the WordPress menu anchor tags?

Theophrastus answered 24/3, 2017 at 7:53 Comment(1)
To avoid adding classes in the menu UI you can use the 'nav_menu_css_class'. I'll add this to my answer...Assam
A
49

You can do what you need with the WP nav_menu_link_attributes hook:

add_filter( 'nav_menu_link_attributes', function($atts) {
        $atts['class'] = "nav-link";
        return $atts;
}, 100, 1 );

...or if you don't like closures:

function add_link_atts($atts) {
  $atts['class'] = "nav-link";
  return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_link_atts');

Filter menu list items

To avoid using the WordPress menu UI to add classes to the menu list items, you can take advantage of the 'nav_menu_css_class' filter:

add_filter( 'nav_menu_css_class', function($classes) {
    $classes[] = 'nav-item';
    return $classes;
}, 10, 1 );
Assam answered 24/3, 2017 at 9:55 Comment(13)
those filters doesn't appear in wordpress' filter hooks reference: codex.wordpress.org/Plugin_API/Filter_Reference. Sure they exist?Clarineclarinet
nav_menu_link_attributes has worked, I haven't yet tried nav_menu_css_classTheophrastus
@127.0.0.1 Yep, they exist! Check out wp-includes/class-walker-nav-menu.php lines 136 and 179Assam
Glad it worked @TimothyAURA, please consider marking the answer correct.Assam
Ok thanks, i'll look after work. If they do count with my upvote. Its nice to have such things, although they not always are documented :( --EDIT: Ok, i'll take TimothyAURA's word.Clarineclarinet
My thoughts exactly!Assam
DavidCara: feel free to /msg stobrendo through freenode :). (Its me).Clarineclarinet
The problem with this, for me, is, it seems to remove classes WordPress is itself applying, like "active", which means I cannot style for the active menu item.Gobbledygook
Would there be a way to get/set a value for $atts['class'] from wp_nav_menu $arg, rather than hard-coding it ?Connote
Exactly what i was looking for. Thanks Mate.Costello
I have a better solution here. https://mcmap.net/q/434217/-how-to-add-class-to-link-in-wp_nav_menuGoodkin
I have a better solution here. https://mcmap.net/q/434217/-how-to-add-class-to-link-in-wp_nav_menuGoodkin
Care this answer is BAD, the other answer by Lars Flieger is not hard coded and thus a way better solution than this!Anthology
T
15

If you have multiple menus over your site or just want to be flexible. You can extend the wp_nav_menu build-in function:

Just add add_a_class to your wp_nav_menu function:

wp_nav_menu(
    array(
        'theme_location'  => 'primary',
        'depth'           => 2,
        'container'       => 'div',
        'add_a_class'     => 'class1 class2',
        'fallback_cb'     => false,
    )
);

Add the following code in your 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);
Tote answered 13/12, 2020 at 15:33 Comment(0)
N
2

This allows you to add classes ONLY to anchors of SPECIFIC MENU. Just add your classes into $menuClassMap values below.

    function mytheme__menu_anchors_add_css( $atts, $item, $args ) {

        $menuClassMap = [
            'navbar-menu' => 'my-footer-menu-link-class',
            'footer-menu' => 'my-footer-menu-link-class',
        ];

        $additionalClassName = $menuClassMap[$args->menu->slug] ?? '';

        if($additionalClassName){
            if(!array_key_exists('class', $atts)){
                $atts['class'] = '';
            }
            $classList = explode (' ' , $atts['class']);
            $classList[] = $additionalClassName;
            $atts['class'] = implode (' ' , $classList);
        }
        return $atts;

    }

    add_filter( 'nav_menu_link_attributes', 'mytheme__menu_anchors_add_css', 10, 3 );
Nuriel answered 14/2, 2019 at 3:40 Comment(0)
C
0

wp_nav_menu()'s parameters wont allow you to add a class to your links with default's functionality. It would allow you to enclose your <a href="#"></a> within any html like <span class="wrapped-anchor"><a href="#"></a></span> if you use :

<?php 
   $parameters = TimothyAURA->set_specific_parameters_you_want(); // i mean, realy fullfill the array with the options you want based on the docs.
   $parameters['before'] = '<span class="wrapped-anchor">';
   $parameters['after'] = '</span>';
   wp_nav_menu($parameters);

In case you really need to set a class for your anchors you would have to pass a Walker object. You would need to read and understand this specific docs about it, though.

Clarineclarinet answered 24/3, 2017 at 9:47 Comment(1)
not a good solution. I have a much better solution here. https://mcmap.net/q/434217/-how-to-add-class-to-link-in-wp_nav_menuGoodkin

© 2022 - 2024 — McMap. All rights reserved.