Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This code comes from here. It checks for a 'sub_menu' argument in the wp_nav_menu() function, then filters the menu accordingly.

However, it always starts the menu from the current page's parent (not including it in the output), or the current page if it has children but no parents. Ideally, I'd like it to always start from the top level item, even on deeper pages. I'd also like to output the top parent item itself.

The code...

// Submenus - required for the submenu (above) to work
function coepio_submenu( $sorted_menu_items, $args ) {

  if ( isset( $args->sub_menu ) ) {
    $root_id = 0;

    // find the current menu item
    foreach ( $sorted_menu_items as $menu_item ) {
      if ( $menu_item->current ) {
        // set the root id based on whether the current menu item has a parent or not
        $root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
        break;
      }
    }

    $menu_item_parents = array();
    foreach ( $sorted_menu_items as $key => $item ) {
      // init menu_item_parents
      if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;

      if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
        // part of sub-tree: keep!
        $menu_item_parents[] = $item->ID;
      } else {
        // not part of sub-tree: away with it!
        unset( $sorted_menu_items[$key] );
      }
    }
    //print('<pre>' . print_r($sorted_menu_items, true) . '</pre>');
    return $sorted_menu_items;
  } else {
    return $sorted_menu_items;
  }
}
// filter_hook function to react on sub_menu flag
add_filter( 'wp_nav_menu_objects', 'coepio_submenu', 10, 2 );
share|improve this question
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.