Применить класс navbar-dropdown только к первому уровню меню

#html #wordpress #menu #wp-nav-walker

#HTML #wordpress #меню #wp-nav-walker

Вопрос:

Итак, я работаю над созданием Navwalker для WordPress, и я застрял на одном шаге, и, похоже, я не могу понять, как заставить это работать.

Итак, у меня есть меню с выпадающим списком, которое использует navbar-dropdown .

Поэтому я хочу, чтобы start_lvl применялся только к первому выпадающему списку, но не ко второму или третьему уровням.. как бы я мог применить navbar-dropdown только к первому уровню выпадающего меню?

Итак, как показано на рисунке, я хочу, чтобы на первом уровне был navbar-dropdown класс (выделен зеленым), но тогда все остальные уровни ul не будут иметь navbar-dropdown .

Изображение для справки: введите описание изображения здесь

 class Navwalker extends Walker_Nav_Menu {

    public function start_lvl( amp;$output, $depth = 0, $args = array() ) {
        $indent  = str_repeat( "t", $depth );
        $output .= "n$indent<ul role="menu" class="navbar-dropdown">n";
    }

    public function start_el( amp;$output, $item, $depth = 0, $args = array(), $id = 0 ) {

        $custom_classes_from_menu = implode(' ', $item->classes); // turn the WP classes object array to string values

        $liClasses = 'navbar-item ' . $custom_classes_from_menu; // add the values to your classes list

        // If menu it has children
        $hasChildren = $args->walker->has_children;

        $liClasses .= $hasChildren ? " has-dropdown is-hoverable": "";

        if ($hasChildren) {
            $output .= "<li class='" . $liClasses . "'>";
            $output .= "n<a class='navbar-link' href='" . $item->url . "'>" . $item->title . "</a>";
        }
        else {
            $output .= "<a class='" . $liClasses . "' href='" . $item->url . "'>" . $item->title;
        }

        // Adds has_children class to the item so end_el can determine if the current element has children
        if ($hasChildren) {
            $item->classes[] = 'has_children';
        }
    }

    public function end_el(amp;$output, $item, $depth = 0, $args = array(), $id = 0 ){

        if(in_array("has_children", $item->classes)) {

            $output .= "</li>";
        }
        $output .= "</a>";
    }

    public function end_lvl (amp;$output, $depth = 0, $args = array()) {

        $output .= "</ul>";
    }
}
  

Ответ №1:

Пожалуйста, измените вашу функцию start_lvl на это:

 public function start_lvl( amp;$output, $depth = 0, $args = array() ) {
        $indent  = str_repeat( "t", $depth );
        if($depth == 0)
            $output .= "n$indent<ul role="menu" class="navbar-dropdown">n";
        else
            $output .= "n$indent<ul role="menu">n";
    }  

Я надеюсь, что это будет полезно.