Multi Level WordPress Menu
Wrriten by Equal Design | Blog | 18 February 2010
WordPress is an excellent CMS and I have used it on most of the projects that I have worked on recently. The one thing however that can be a little tricky is multi-level page menus, when you have got several levels of parent/sub pages. Whilst working on a large project recently I have come across a pretty good way of getting round this problem.
I was working on a site that required a multi-level page navigation system. This primarily meant that when viewing a page the child pages of that page would need to be displayed in the sites sidebar. That in itself it not that difficult, but when you get several levels of pages it can be tricky. The code below is what I am using which seems to work OK. I will explain it beneath.
<?php global $post; $thispage = $post->ID; ?>
<?php $pagekids = get_pages("child_of=".$thispage."&sort_column=menu_order"); ?>
<?php if ($pagekids) { ?>
<h2>
<?php the_title(); ?>
</h2>
<ul>
<?php wp_list_pages("depth=1&title_li=&sort_column=menu_order&child_of=".$thispage); ?>
</ul>
<?php } else { ?>
<?php $ancestors = get_post_ancestors($post->ID); ?>
<?php if($ancestors) { ?>
<h2>
<?php the_title(); ?>
</h2>
<ul>
<?php wp_list_pages("depth=1&title_li=&sort_column=menu_order&child_of=".$post->post_parent); ?>
</ul>
<?php } else { ?>
<h2>
<?php the_title(); ?>
</h2>
<?php } ?>
<?php } ?>
The first line of the code is all about getting the current page ID. The code retrieves the page ID and stores this in a PHP variable $thispage. The second line gets a list of all the child pages of the current page and stores then in the PHP variable $pagekids. We then check whether $pagekids has any values or not. If there are some values it means the current page has children, so we display them, if there are not any values then it means that the current page has no children. If this is the case then we check to see if the current page has any ancestors. If the current page has ancestors then we display a list of siblings and if there are no answers then it must mean that we are a the top level of pages and we can display nothing.