将导航栏下拉菜单仅应用于菜单的第一级

问题描述

因此,我正在为WordPress构建Navwalker,我只停留在一个步骤上,而我似乎无法弄清楚如何实现此目的。

所以我有一个带有下拉菜单的菜单,该菜单使用navbar-dropdown

所以我想将start_lvl仅应用于第一下拉菜单,而不应用于第二或第三级。我如何将导航栏下拉菜单仅应用于菜单下拉菜单的第一级?

因此,如图所示,我希望第一个级别具有navbar-dropdown类(以绿色突出显示),但其他所有ul级别则不具有navbar-dropdown

图片供参考:

enter image description here

class Navwalker extends Walker_Nav_Menu {

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

    public function start_el( &$output,$item,$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(&$output,$id = 0 ){

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

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

    public function end_lvl (&$output,$args = array()) {

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

解决方法

请将您的start_lvl函数更改为此:

public function start_lvl( &$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";
    }

我希望这会有所帮助。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...