Fast and simple 3-level-navigation for Wordpress: show top level, parent and subpages only when on a subpage
Every now and then, we're using Wordpress as a CMS for clients' sites that require only basic content and navigation.
What bugs me every time is the navigation. For me, a reasonable navigation is able to show up to 3 sublevels, and when a menu item is clicked, it lists all of its subpages, and when a subpage is clicked, it lists its subpages and so on.
What's important here is to have the parent and ancestor pages (or top level pages) stay where they are when you dig deeper. Even if there is a breadcrumb available, most users tend to use the main navigation to return to the previous level. Plus, this sort of step-by-step navigation gives the user a reasonable overview of his or her possible options.
Navigation ( active links are bold):
a)
- Home
- -Subpage 1
- -Subpage 2
- -Subpage 3
b)
Subpage 1
- Subpage 1
- -Subpage 1.1
- -Subpage 1.2
- -Subpage 2 (this site has children too, but they only show when the item is clicked)
- -Subpage 3
c)
Subpage 1
- Subpage 1
- -Subpage 1.1
- -Subpage 1.2
- -Subpage 2
- -Subpage 3
There are many ways to create that sort of navigation, but they all have in common that you need to have a certain level of PHP knowledge.
The basic code snippet to get a list of pages is <?php wp_list_pages(); ?> with its arguments. You can combine it with a walker function if you need more specific functions.
I have to admit I prefer writing my own function than using any kind of plugin to do it for me. But this time I'm giving in.
The Simple Section Navigation Plugin does exactly what we need, and nothing else. It's slim and it works. You can use it as a widget in your sidebar, but you can as well call it from inside of your template file.
It also puts the title of the top level page above the navigation. If you don't want that, go into the plugin's php-file and on line 96 simply change
echo $before_widget.$before_title.$sect_title.$after_title."<ul>";
to
echo $before_widget."<ul>";
By this you only prevent the output of this part of the widget. (h3 and section title)
Other useful code snippets:
1) Echo the title of the top level page (in a 3-level-navigation level 0)
global $post; $post_ancestors = get_post_ancestors($post); $top_page = $post_ancestors ? end($post_ancestors) : $post->ID; $toptitle = get_the_title($top_page); echo $toptitle;
2) Echo the title of the parent page (in a 3-level-navigation level 1 or 2, depending on which subpage you're on)
$parent_title = get_the_title($post->post_parent); echo $parent_title;
(Plugin Version 2.1., Wordpress 3.1.2)




Comments [0]