Search code examples
wordpresswordpress-theming

Add class to anchors in WordPress Menus


I'm trying to add the standard Bootstrap nav-link class to the anchors rendered by the WordPress menu.

  1. I can pass variables to the wp_nav_menu() which applies a class to the menu (and remove the containing):

    <?php wp_nav_menu(array(
        'theme_location' => 'header-menu',
        'menu_class' => 'navbar-nav',
        'container' => 'false'
    ) );
    ?>
    
  2. I then use the WordPress Appearances > Menu UI to apply nav-item class to <li> tags.

How do I apply a class to the WordPress menu anchor tags?


Solution

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