Filtering the WordPress Menu

You can filter both the <li> tag and the contained anchor tag in a WordPress menu using the ‘nav_menu_css_class’ and ‘nav_menu_link_attributes’ filters.

The ‘nav_menu_link_attributes’ filter is not well documented – but very useful nonetheless.

This example shows how to add the required classes for a Bootstrap 4 menu markup – in which the <li> requires the class nav-item and the anchor tag requires the class nav-link:

<?php
add_filter( 'nav_menu_css_class', function($classes) {
$classes[] = 'nav-item';
return $classes;
}, 10, 1 );

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