If your site has multiple navigational levels then it’s sometimes useful to include a sidebar widget that displays an easy way for the user to select child or sibling pages. WordPress’ wp_list_pages function allows us to create this functionality.
Displaying only Sibling Pages with wp_list_pages
Suppose your have a navigation similar to the structure below:
Suppose the user is on the “Sports” page. You’d want the sidebar widget to display the subpage items for that section like so:
Now the user clicks on “Golf” and they are no longer on the “Sports” page, it is now the parent page. The sidebar will then display sibling pages and exclude the page the currently is on:
How to Achieve this with Code
There may be a few different ways to achieve this with code, but this is the method that I found works best for my needs:
What’s going on here? First we are checking to see if the current page has any child pages using the get_pages function. Next, we check to see if the current page has a parent. If the parent page does have children then we display the child pages for that section by declaring separate arguments using the ‘child_of’ this post ID parameter.
If the current page does not have any children then it’s time to query the post parent’s page list. We can’t forget to use the ‘exclude’ parameter to make sure the current page the user on is not displayed as well in the page list.
To Wrap it Up
As you can see this can be a helpful widget and it’s easy to setup and style. I haven’t tested the code above with more than just 2-levels of pages. Let me know if it works for you!