1

My question relates to showing the parents and siblings of the current page.

If I am on level 2 page, I would like to show siblings without their children. If I am on level 3 page, I would like to show siblings, parent and parent's siblings.

For example if I would have page levels like this:

Animals (level 1)
- Fish (level 2)
-- Salmon (level 3)
-- Trout
-- Pike
- Mammals
-- Dogs
-- Cats
Plants

If I am on the page Fish, I would like to show siblings:

Fish
Mammals

If I am on the page Salmon, I would like to show siblings, parent and parents siblings:

Fish
- Salmon
- Trout
- Pike
Mammals

My current code looks like this:

<?php
if($post->post_parent)
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&sort_column=menu_order");
else $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&sort_column=menu_order");
if ($children) { ?>
<ul><?php echo $children; ?></ul>
<?php } ?>

1 Answer 1

1

As it stands your code almost works, but it checks to see if the current page has a parent, which will always be true for both 2nd and 3rd level pages.

WordPress gives us get_ancestors to retrieve an ordered array of ancestors for any hierarchical object type:

get_ancestors( $object_id, $object_type );

So we can use get_ancestors( $post->ID, 'page' ) and count the elements to help us get the depth right for your navigation.

if($post->post_parent) {

    $ancestors = get_ancestors( $post->ID, 'page' );

    if ( 1 == count( $ancestors ) ) {

            echo '<ul>';

            wp_list_pages(
                array (
                    'title_li' => '',
                    'sort_column' => 'menu_order',
                    'child_of' => $ancestors[0],
                    'depth' => 1
                ) 
            );

            echo '</ul>';

    }

    if ( 2 == count( $ancestors ) ) {

            echo '<ul>';

            wp_list_pages(
                array (
                    'title_li' => '',
                    'sort_column' => 'menu_order',
                    'child_of' => $ancestors[1],
                    'depth' => 2
                ) 
            );

            echo '</ul>';

    }


}

You could be more clever with the logic, popping the last element off the ancestor array for example, but I've kept it verbose for clarity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.