treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] wp_nav_menu strange behaviour with custom walker

  • Hi guys,

    I have a strange problem in wordpress using a custom walker.

    This is my call for the menu:

    <?php /* Dynamic menu if available */
      wp_nav_menu(
      array(
      'menu'=>'Home Menu',
      'container_class'=>'menu group',
      'container'=>'nav',
      'items_wrap' => '%3$s',
      'depth'=> 0,
      'walker'=> new walker()
      )
      )
      ?>
    

    And this is my walker class

    class walker extends Walker_Nav_Menu
    {
    function start_el(&$output, $item, $depth, $args)
    {
    global $wp_query;
    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    
    $class_names = $value = '';
    
    $classes = empty( $item->classes ) ? array() : (array) $item->classes;
    
    $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
    $class_names = ' class="'. esc_attr( $class_names ) . '"';
    
    $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
    $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
    $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
    
    if($depth != 0)
    {
    $description = $append = $prepend = "";
    }
    
    $item_output = $args->before;
    $item_output .= '<a id="menu-item-'. $item->ID . '"' . $value . $class_names . $attributes .'>';
    $item_output .= $args->link_before .$prepend.apply_filters( 'the_title', $item->title, $item->ID ).$append;
    $item_output .= '</a>';
    $item_output .= $args->after;
    
    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
    }
    

    My output looks like this:

    <nav class="menu group"><a id="menu-item-256" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-home" href="">Title</a></li>
    </nav>
    

    I really don't understand, where the closing </ li> is coming from...

  • Is it not coming from that second to last line of the walker.

    $item_output .= $args->after

    If you remove that, it should remove the closing LI, but it might break the menu. It might not.

  • Already tried that and commented that line out. No difference...

  • Just found it myself. By extending Walker_Nav_Menu you also extend the end_el function.

    Guess what is in there by default?

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "</li>\n";
    }
    

    So by simply adding my own reference in my function.php I could fix it.

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
    $output .= "\n";
    }