I found this very useful code at the wp codex, it basically lists out the parent, child and grandchild pages, I’m using it in my sidebar and it works well for the parent and children pages, but when you go to a grandchild page, the menu changes and it now only shows the child/grandchild, instead of the same menu on the parent & child pages. how can i make it show the same on all the pages?
Also i’d like the parent title to be an actual link rather than just text and I can’t seem to figure that out. help is greatly appreciated!!
<?php
if($post->post_parent) {
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
$titlenamer = get_the_title($post->post_parent) ;
}
else {
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
$titlenamer = get_the_title($post->ID);
}
if ($children) { ?>
<h2> <?php echo $titlenamer; ?> </h2>
<ul>
<?php echo $children; ?>
</ul>
<?php } ?>
https://gist.github.com/3853924
This is a plugin I created and usually use for this type of functionality. The key is the little function down at the bottom of the file that searches for the top-level ancestor. There’s also part of the code that will print out categories instead of pages when you’re on a blog or search page; you can turn it off by commenting out line 43.
It will display as many levels of page hierarchy as you care to make, and it will always display the top-level parent page levels.
You can install it by downloading the file, adding it to your plugins folder, and activating. If you want to use it in your code rather than a widget area, you can do something like this:
The pertinent part of the widget is this:
and this:
Then wherever you want to get a list of sub-pages/sibling pages:
<?php related_pages(); ?>
The reason behavior changes is because that code only checks for immediate parent. So it doesn’t go looking for parent of a child.
To go through whole hierarchy you would need to retrieve and process it with
get_post_ancestors()
.I finally figured this out. I didn’t want it to show up at all on pages without children, so the first if statement checks and only displays the menu if the parent has children. This menu stays the same whether you are on the parent, child, or grandchild page. 🙂