php 如何检查步行者_Nav_Menu中的菜单项类

vs91vp4v  于 2023-02-11  发布在  PHP
关注(0)|答案(1)|浏览(123)

我有一个自定义的两级菜单在WordPress中。有一个上层,当你悬停在项目,出现了一个子菜单。2子菜单中的两个菜单项有一个按钮,而其他子菜单中没有。3这两个段落有一个“browseall”类。4我需要在步行者_Nav_Menu中检查这个类,并向子菜单添加一个自定义按钮。5我如何检查“browseall”类?6在我的代码中,我'我正在为ul.sub-menu创建一个 Package 器。我需要检查元素中是否有一个“browseall”类,以便在这个 Package 器中添加一个按钮。这样的按钮只会出现在有“browseall”类的项目中。

class My_Walker extends Walker_Nav_Menu {
  function start_lvl( & $output, $depth = 0, $args = array()) {
    $indent = str_repeat("\t", $depth);
    if ($depth == 0) {
      $output. = "\n$indent<div class='sub-menu__depth-1'><ul class='sub-menu sub-menu__main'>\n";
    } else {
      $output. = "\n$indent<ul class='sub-menu'>\n";
    }
  }

  function end_lvl( & $output, $depth = 0, $args = array()) {
    $indent = str_repeat("\t", $depth);
    if ($depth == 0) {
      $output. = "$indent</ul> <
        /div>\n";
    } else {
      $output. = "$indent</ul>\n";
    }
  }
}

下面是一个应该如何的例子:

class My_Walker extends Walker_Nav_Menu
{
    function start_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);
        if ($depth == 0) {
            $output .= "\n$indent<div class='sub-menu__depth-1'><ul class='sub-menu sub-menu__main'>\n";
        } else {
            $output .= "\n$indent<ul class='sub-menu'>\n";
        }
    }
    function end_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);
        if ($depth == 0) {
    //here, a button appears outside the sub-menu if the navigation element has the class "browse all"
            $output .= "$indent</ul>
    <a>Browse All</a>        
    </div>\n";
        } else {
            $output .= "$indent</ul>\n";
        }
    }
}
kgsdhlau

kgsdhlau1#

我不认为您可以直接在start_lvlend_level中执行此操作-因为它们只创建 Package UL。但它们没有您要查找的类,这些类位于实际的导航项中,并且在start_elend_el中处理/呈现。
但是我想你可以给这个类添加一个属性,一个数组--在这个数组中你可以保存信息,不管特定深度的当前(子)菜单是否需要添加这些额外的元素。

class My_Walker extends Walker_Nav_Menu {

  private $needsCustomButtons = [];

  function start_lvl( & $output, $depth = 0, $args = array()) {
    $this->needsCustomButtons[$depth] = false;
    
    // rest of the stuff that needs doing here
  }

  public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) {
    // stuff

    $classes   = empty( $menu_item->classes ) ? array() : (array) $menu_item->classes;
    $classes[] = 'menu-item-' . $menu_item->ID;

    if(in_array('browse-all', $classes)) {
      $this->needsCustomButtons[$depth] = true;
    }

    // more stuff here

  }

  function end_lvl( & $output, $depth = 0, $args = array()) {
    // if $this->needsCustomButtons[$depth] is true here, then you know
    // your two extra nav items need adding, so concatenate them to
    // $output here, before the closing `</li>` tag gets added.
  }
}

相关问题