Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress Menu - Add class to anchors

Trying to add the standard bootstrap "nav-link" class to the anchors rendered by the Wordpress menu. So far ...

1/ I can pass variables to the wp_nav_menu()

<?php wp_nav_menu(array(
                            'theme_location' => 'header-menu',
                            'menu_class' => 'navbar-nav',
                            'container' => 'false'
        ) );
        ?>

and apply a class to the menu that way, and remove the containing div.

2/ I then use the Wordpress Appearances > Menu UI to apply "nav-item" class to li tags.

Q. How do I apply a class to the wordpress menu anchor's

like image 382
TimothyAURA Avatar asked Mar 24 '17 07:03

TimothyAURA


1 Answers

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 );
like image 155
csknk Avatar answered Sep 20 '22 17:09

csknk