Keep page hierarchy in wp_list_pages, even if on a child or grandchild

百般思念 提交于 2021-01-29 07:03:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!