0

次のページ構造があり、子ページを持つページに同じ構造を表示する必要があります。

- Childpage
- - Grandchildpage
- - Other Grandchildpage
- Other Childpage

次のコードは、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>

これは、親ページで機能します。しかし、子ページまたは孫ページのいずれかを使用している場合、これは機能しなくなります。

上記の構造例に従って、「チャイルドページ」を使用しているときは、次のように表示されます。

- Childpage
- Other Childpage

そして、「孫のページ」にいるときは、次のようになります。

- - Grandchildpage
- - Other Grandchildpage

ページが子または孫の場合でもページ階層を表示する正しい方法は何ですか?

4

1 に答える 1

2

以下のコードを使用します。

<?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 } ?>
于 2015-12-18T12:57:38.213 に答える