Wordpress Menu - Add class to anchors
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);
If you want to add a class in anchor tag for a specific menu then can use following steps
Step-1: add this in functions.php
function add_class_on_a_tag($classes, $item, $args)
{
if (isset($args->add_a_class)) {
$classes['class'] = $args->add_a_class;
}
return $classes;
}
add_filter('nav_menu_link_attributes', 'add_class_on_a_tag', 1, 3);
Step-2:- use it like this in your theme
<?php
// Show Menu here
wp_nav_menu(array(
'theme_location' => 'my-menu',
'menu_class' => 'footer-top',
'add_a_class' => 'nav-link',
));
?>
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 );
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 );