【问题标题】:How to check menu item class in Walker_Nav_Menu如何检查 Walker_Nav_Menu 中的菜单项类
【发布时间】:2023-02-08 20:17:24
【问题描述】:

我在 WordPress 中有一个自定义的两级菜单。有一个上层,当您将鼠标悬停在项目上时,会出现一个子菜单。子菜单中的两个菜单项具有其他子菜单中没有的按钮。这两段都有“浏览全部”类。我需要在 Walker_Nav_Menu 中检查此类并向子菜单添加自定义按钮。我怎样才能检查类“浏览所有”? 在我的代码中,我正在为 ul.sub-menu 创建一个包装器。我需要检查元素中是否有“浏览所有”类,以便向此包装器添加按钮。这样的按钮只会出现在“浏览所有”类的项目中。

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

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    我认为您不能直接在 start_lvlend_level 中执行此操作 - 因为它们只会创建包装 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.
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多