Third level navigation class

时间:2019-01-24 作者:Jonas

我目前正在进行三级导航。输出应如下所示:

<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>
有没有办法将自定义类添加到第三级列表中?我用一个定制的步行者完成了第二级:

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";
    }
}

1 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

你不需要为此编写自定义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 );