Alright, so I usually use wp_list_pages to create my menus. This usually works pretty well, but every now and then a project comes along that requires more than the functionality provided by the wp_list_pages function.
So maybe you want a menu that should have a nested sub menu when viewing a page and/or child to one of the “main pages”.
This could be done by passing a custom Walker to the wp_list_pages function.
class Custom_Walker_Page extends Walker_Page {
function start_el(&$output, $page, $depth, $args, $current_page) {
extract($args, EXTR_SKIP);
$css_class = array();
$extra = '';
if ( !empty($current_page) ) {
$_current_page = get_page( $current_page );
if ( ( isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors) ) || ( $page->ID == $current_page ) || ( $_current_page && $page->ID == $_current_page->post_parent ) )
$css_class[] = 'sel';
if ( $page->ID == $current_page || in_array($page->ID, (array) $_current_page->ancestors) ) {
$sub = $current_page;
if( count($_current_page->ancestors) > 1 )
$sub = $_current_page->ancestors[0];
$extra = wp_list_pages('title_li=&echo=0&child_of=' . $sub );
if ( $extra )
$extra = '<ul class="sub">' . $extra . '</ul>';
}
}
$css_class = implode(' ', apply_filters('page_css_class', $css_class, $page));
$output .= '<li' (="" $css_class="" ?="" class="' . $css_class . '" :="" )="" .=""><a href="%27%20.%20get_page_link%28$page-%3EID%29%20.%20%27" title="' . esc_attr( wp_strip_all_tags( apply_filters( 'the_title', $page->post_title ) ) ) . '"><span>' . apply_filters( 'the_title', $page->post_title ) . '</span></a>';
$output .= $extra;
}
}
And then pass it to the wp_list_pages function:
$walker = new Custom_Walker_Page();
wp_list_pages( array( 'child_of' => $parent_id, 'depth' => 1, 'walker' => $walker) );
I guess this is pretty advanced stuff, so I have created some new categories. This post falls into the “Advanced” category.