0

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?

3
  • If you're using wp_nav_menu, you should have the whole nav prebuilt in Admin -> Appearance -> Menus. Are you building the nav menu on the fly? Apr 29, 2011 at 0:39
  • I don't want the sub-categories displaying by default, only when the user is on the applicable category
    – Stoosh
    Apr 29, 2011 at 0:51
  • Just to be clear, an unacceptable solution would be one that prints out all sub categories for all categories and the non-current category sub-categories are hidden? If that doesn't work, I don't think you can accomplish this with wp_nav_menu. Rather, I think you'd have to write a function that first looks to see what the parent is and then generates the menu and only displays the sub categories for the current parent.
    – tollmanz
    Apr 29, 2011 at 2:00

1 Answer 1

3
+100

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

2
  • Thanks for the insight, I wasn't aware of the display_element method in the Walker class. I'll go through it a bit later and let you know the results
    – Stoosh
    May 4, 2011 at 2:25
  • Genius! Worked well enough for me to modify to get it how I want it! Thanks.
    – Stoosh
    May 4, 2011 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.