问题
I have the following structure of pages, and I need to have that same structure displayed on those pages who have child pages:
- Childpage
- - Grandchildpage
- - Other Grandchildpage
- Other Childpage
The following code is used to display the structure on page.php:
<ul class="sidemenu-list">
<?php
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=1");
else
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=1");
if ($children) { ?>
<ul>
<?php echo $children; ?>
</ul>
<?php } ?>
</ul>
This works when on the parent page. But when I'm on one of the childpages or grandchild pages, this doesn't work anymore.
Following above structure example, when I'm on 'Childpage' I only get the following:
- Childpage
- Other Childpage
And when I'm on 'Grandchildpage' I only get:
- - Grandchildpage
- - Other Grandchildpage
What is the correct way to display the page hierarchy even when the page is a child or grandchild?
回答1:
Use the code below:
<?php
if(!$post->post_parent){
// get the child of the top-level page
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
}else{
// get the child pages if we are on the first page of the child level.
//$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
if($post->ancestors)
{
// now get an ID of the first page
// wordpress collects ID in reverse order, so the "first" will be the last page
$ancestors = end($post->ancestors);
$children = wp_list_pages("title_li=&child_of=".$ancestors."&echo=0");
}
}
if ($children) { ?>
<ul>
<?php echo $children; ?>
</ul>
<?php } ?>
来源:https://stackoverflow.com/questions/33155726/keep-page-hierarchy-in-wp-list-pages-even-if-on-a-child-or-grandchild