没有UL的WordPress Walker:在父级中包含子菜单

时间:2018-09-19 05:54:23

标签: wordpress wp-nav-walker

我对WordPress的助行器不太满意,但我需要制作一个基于nav > div > ul > li > a而不是基于nav > a的标题菜单。到现在为止,我已经将它覆盖了,但是随后我遇到了一个问题:助步器使子菜单超出了它的父级;所以不用:

<nav>
  <div> <!-- parent menu item -->
    <span>text</span>
    <a>text</a> <!-- submenu item -->
    <a>text</a> <!-- submenu item -->
  </div>
  <a>text</a> <!-- normal menu item -->
  <a>text</a> <!-- normal menu item -->
  <a>text</a> <!-- normal menu item -->
</nav>

我得到:

<nav>
  <div> <!-- parent menu item -->
    <span>text</span>
  </div>
  <ul class="sub-menu"> <!-- child menu -->
    <a>text</a> <!--submenu item -->
    <a>text</a> <!--submenu item -->
  </ul>
  <a>text</a> <!-- normal menu item -->
  <a>text</a> <!-- normal menu item -->
  <a>text</a> <!-- normal menu item -->
</nav>

我真的不知道如何将子菜单放回父菜单。这是我当前的代码:

class walkerMenuDoTopo extends Walker_Nav_Menu {

    function start_el(&$output, $item, $depth = 0, $args) {
        $class_names = $value = '';

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

        $class_names = join(' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args) );
        !empty ( $class_names ) and $class_names = ' class="nav-link w-nav-link '. esc_attr( $class_names ) . '"';

        $output .= "";
        $attributes  = '';
        !empty( $item->attr_title ) and $attributes .= ' title="'  . esc_attr( $item->attr_title ) .'"';
        !empty( $item->target ) and $attributes .= ' target="' . esc_attr( $item->target ) .'"';
        !empty( $item->xfn ) and $attributes .= ' rel="'    . esc_attr( $item->xfn ) .'"';
        !empty( $item->url ) and $attributes .= ' href="'   . esc_attr( $item->url ) .'"';

        $title = apply_filters( 'the_title', $item->title, $item->ID );

        $item_output = $args->before
        . "<a $class_names $attributes>"
        . $args->link_before
        . $title
        . '</a>'
        . $args->link_after
        . $args->after;

        if($args->has_children) {
          $class_names = ' class="dropdown-toggle w-dropdown-toggle nav-link w-nav-link '. esc_attr( $class_names ) . '"';
          $attributes .= ' data-hover="1" data-delay="250"';

          $item_output = $args->before
          . "<div $class_names><span>"
          . $args->link_before
          . $title
          . '</span></div>'
          . $args->link_after
          . $args->after;
        }
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }

    function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
      $id_field = $this->db_fields['id'];
      if ( is_object( $args[0] ) ) {
        $args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
      }
      return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
}

0 个答案:

没有答案