简体   繁体   中英

Displaying sub-categories in sidebar when parent category selected

What I'm trying to achieve in WP 3.1.x using the wp_nav_menu function, is to have a menu such as:

-- Category 1
-- Category 2
-- Category 3
-- Category 4
-- Category 5
-- Category 6

But when you're on 'Category 2' it displays as:

-- Category 1
-- Category 2
  -- Sub Category 1
  -- Sub Category 2
  -- Sub Category 3
-- Category 3
-- Category 4
-- Category 5
-- Category 6

PS. I'm not looking for CSS hide/show functionality, that can be achieved easily.

PPS. Is a possible solution for this extending the Walker_Nav_Menu class?

If you subclass the Walker_Nav_Menu class you can override the display_element function and conditionally remove an item's children before they are looped through.

if (!$element->current && !$element->current_item_ancestor && isset( $children_elements[$id])) {
   unset( $children_elements[ $id ] );
}

This would remove the children of any item that is not current, so you would need to check the item's type if you just want to do this for categories. The complete walker would look something like this: https://gist.github.com/954627

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM