2
\$\begingroup\$

The goal here is to create a Top Level Menu that automatically pulls child pages without the need to manually add them to said menu. I didn't know any other way to accomplish this without a walker, of which I'm not very familiar with.

I was playing around with it and was able to get the submenus to work with this. The submenu gets added at the bottom of start_el

/** The Walker **/
class fitz_and_the_tantrums extends Walker_Nav_Menu {

    // add main/sub classes to li's and links
     function start_el( &$output, $item, $depth, $args ) {
        global $wp_query;
        $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent

        // passed classes
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;

        $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) );

        // build html
        $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $class_names . '">';

        // link attributes
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $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        ) .'"' : '';
        $attributes .= ' class="menu-link ' . ( $depth > 0 ? 'sub-menu-link' : 'main-menu-link' ) . '"';

        $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s',
            $args->before,
            $attributes,
            $args->link_before,
            apply_filters( 'the_title', $item->title, $item->ID ),
            $args->link_after,
            $args->after
        );

        // build html
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );

        if(nav_hasChildren($item->object_id)){
            $output .= '<ul class="submenu">';
            ob_start();
                wp_list_pages(
                    array(
                        'child_of'  => $item->object_id,
                        'depth'     => 1,
                        'title_li'  => ''
                    )
                );
            $output .= ob_get_clean();
            $output .= '</ul>';
        }
    }
}

/** Check if item has Children **/
function nav_hasChildren($pid) {
    $children = get_pages('child_of='.$pid);
    if($children)
        return true;
    else
        return false;
}

Is there a way to minimize the needed code, or do I absolutely need to set everything so that the Walker can function properly?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.