I'm currently working on a third level navigation. The output should something like this:
<ul class="menu">
<li>
<a href="#">Level 1</a>
<ul class="sub">
<li>
<a href="#">Level 2</a>
<ul class="subsub">
<li><a href="#">Level 3</a>
</ul>
</li>
</ul>
</li>
</ul>
Is there a way to add a custom class to the third level list? I've done this for level two with a custom walker:
class Main_Nav_Walker extends Walker_Nav_Menu {
function start_lvl(&$output, $depth = 0, $args = Array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"sub\">\n";
}
}
I'm currently working on a third level navigation. The output should something like this:
<ul class="menu">
<li>
<a href="#">Level 1</a>
<ul class="sub">
<li>
<a href="#">Level 2</a>
<ul class="subsub">
<li><a href="#">Level 3</a>
</ul>
</li>
</ul>
</li>
</ul>
Is there a way to add a custom class to the third level list? I've done this for level two with a custom walker:
class Main_Nav_Walker extends Walker_Nav_Menu {
function start_lvl(&$output, $depth = 0, $args = Array() ) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"sub\">\n";
}
}
You don't need to write your custom Walker for that...
Let's take a look on built-in Walker_Nav_Menu
. You'll find this function:
public function start_lvl( &$output, $depth = 0, $args = array() ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
// Default class.
$classes = array( 'sub-menu' );
/**
* Filters the CSS class(es) applied to a menu list element.
*
* @since 4.8.0
*
* @param array $classes The CSS classes that are applied to the menu `<ul>` element.
* @param stdClass $args An object of `wp_nav_menu()` arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = join( ' ', apply_filters( 'nav_menu_submenu_css_class', $classes, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
$output .= "{$n}{$indent}<ul$class_names>{$n}";
}
As you can see, there is a filter (nav_menu_submenu_css_class
) in there that will allow you to modify classes of the list item.
So all you have to do is to add your filter to that hook:
function change_ul_item_classes_in_nav( $classes, $args, $depth ) {
if ( 0 == $depth ) {
$classes[] = 'sub';
}
if ( 1 == $depth ) {
$classes[] = 'subsub';
}
// ...
return $classes;
}
add_filter( 'nav_menu_submenu_css_class', 'change_ul_item_classes_in_nav', 10, 3 );