Yes, it is possible.
You can achieve this using wp_nav_menu_objects
filter.
function my_wp_nav_menu_objects($objects, $args) {
foreach($objects as $key => $item) {
$objects[$key]->classes[] = 'my-class';
}
return $objects;
}
add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);
The only problem is that these classes will be added to li
elements and not to links directly. But it’s default WordPress behavior and I don’t think you should change it.
If you really have to change it, it is still possible:
function my_walker_nav_menu_start_el($item_output, $item, $depth, $args) {
// you can put your if statements in here (use item, depth and args in conditions)
if ( $depth == 1 ) {
$item_output = preg_replace('/<a /', '<a class="level-1-menu" ', $item_output, 1);
} else if ( $depth == 2 )
$item_output = preg_replace('/<a /', '<a class="level-2-menu" ', $item_output, 1);
}
// .. and so on
return $item_output;
}
add_filter('walker_nav_menu_start_el', 'my_walker_nav_menu_start_el', 10, 4);