How to filter the sub-menu classname in WordPress navigation menus?

In WordPress when using navigation menus, second-level menus are given the class sub-menu. For example:

<ul>
    <li>
        <a title="Page 1" href="/page-1/">Page 1</a>
        <ul class="sub-menu">
            <li>
                <a title="Sub page 1" href="/sub-page-1/">Sub page 1</a>
            </li>
            <li>
                <a title="Sub page 2" href="/sub-page-2/">Sub page 2</a>
            </li>
        </ul>
    </li>
</ul>

I’m using Bootstrap 3 so need that classname to be dropdown-menu. My attempt so far has been to copy all of the dropdown-menu classes from bootstrap.css into my theme’s style.css and change their names to sub-menu. This isn’t a great approach because when I next upgrade Bootstrap, I’ll need to check anything hasn’t changed.

Read More

My next thought was to filter the classname. Does WordPress provide a filter which will let me change this classname?

Update

I found a walker solution here which lets me change the sub-menu class.

class My_Walker_Nav_Menu extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("t", $depth);
    $output .= "n$indent<ul class="my-sub-menu">n";
  }
}

I’m pasting this directly into my theme’s functions.php. This allows me to change the classname but my problem now is I get the following PHP debug notice:

Strict Standards: Declaration of My_Walker_Nav_Menu::start_lvl()
should be compatible with Walker_Nav_Menu::start_lvl(&$output, $depth
= 0, $args = Array) in /wp-content/themes/my-theme/functions.php
on line 224

Should I be pasting the walker directly into my theme’s functions.php? Where am I going wrong?

Related posts

Leave a Reply

2 comments

  1. Why don’t you do the opposite? Instead of editing the CSS, edit the theme file. You could just change the ul’s class.

    <ul class="dropdown-menu">
       ...
    </ul>
    

    If you need to keep the “sub-menu” class in the ul for any reason, you can also use both in the same element. Just add the “bootstrap.css” class to the ul.

    <ul class="sub-menu dropdown-menu">
       ...
    </ul>
    
  2. You need to include your walker file in functions.php and change in your wp_nav_menu function to call walker like this…

    wp_nav_menu( array(
        'menu'              => 'Main Navigation',
        'theme_location'    => 'main_navigation',
        'depth'             => 0,
        'container'         => 'div',
        'container_class'   => 'collapse navbar-collapse',
        'container_id'      => 'bs-example-navbar-collapse-1',
        'menu_class'        => 'nav navbar-nav',
        'fallback_cb'       => 'wp_bootstrap_navwalker::fallback',
        'walker'            => new wp_bootstrap_navwalker())
    );