Dev Notes

Software Development Resources by David Egan.

Filtering the WordPress Menu

Bootstrap 4, PHP, WordPress
David Egan

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’ and ‘nav_menu_css_class’ filters are not well documented - but very useful nonetheless. You can see the filters in wp-includes/class-walker-nav-menu.php on line 136 and 179.

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:

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 );

comments powered by Disqus