【问题标题】:Apply the navbar-dropdown class to just the first level of a menu仅将 navbar-dropdown 类应用于菜单的第一级
【发布时间】:2020-12-06 00:11:48
【问题描述】:

所以我正在为 WordPress 构建一个 Navwalker,但我卡在了一个步骤上,我似乎无法弄清楚如何完成这项工作。

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

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

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

图片供参考:

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, $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(&$output, $item, $depth = 0, $args = array(), $id = 0 ){

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

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

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

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

【问题讨论】:

    标签: html wordpress menu wp-nav-walker


    【解决方案1】:

    请将您的 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";
        }

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2015-09-23
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多