How to Create a Sidebar Navigation Menu with Parent and Child Pages

For a recent Saas application we are working on, I ran into the challenge of creating a WordPress template page that displayed a menu in the sidebar of the page with the Parent Page as the first list item, followed by the child pages of that parent. The function in use is wp_list_pages(), which can accept a pretty wide range of parameters to allow for various customization. For more info about this particular function, see the WordPress Codex at http://codex.wordpress.org/Function_Reference/wp_list_pages

The Problem

The problem I ran into was the inability to display the Parent page in the menu with the child pages while I was on both parent or child pages. Wp_list_pages() has both a “child_of” and “include” parameters, but the problem is that the “include” parameter overrides the child_of value and just displays the one ID passed to it.

 The Solution

The solution was pretty simple, but sometimes the simple solution are the ones most easily overlooked. Since wp_list_pages() only outputs the link in an <li> tag without any <ul> or <ol> containers, I simply called it twice, once to get and echo the parent page and a second time to get and echo the child pages.

code

The first call, $parent, tells WordPress to either get the post parent page if we’re on a child page, or get the page ID itself if we are not on a child page (i.e. we’re on the parent page). The second call, $children, basically does the opposite. Then by just echoing both variables in a single <ul></ul> list, the result is a smooth menu list without any hacky fixes, or hard coded links.

The Result

code2

code3

July 15, 2013 by meritadmin Category: Software 0 comments

Recent Posts