你不需要为此编写自定义Walker。。。
让我们看看内置的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}";
}
如您所见,有一个过滤器(
nav_menu_submenu_css_class
) 这将允许您修改列表项的类。
因此,您只需将过滤器添加到挂钩:
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 );