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
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');
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With