Display grandchildren on child and grandchild pages using wp_list_pages

So if I have this straight:

IF We are currently viewing a Top Level Page THEN Show Nothing

IF We are currently viewing a Child Page THEN Show Grandchildren

IF We are currently viewing a Grandchild Page THEN Show Grandchildren

If the above logic is correct we can use something like this:

$id = get_ancestor(); // Hold Top Most Page ID

<?php if($post->post_parent != 0) : /** IF we're NOT on a Top Level Page **/ ?>
    <ul>
        <?php 
            $parentID = ($post->post_parent == $id) ? $post->ID : $post->post_parent;
            wp_list_pages("child_of=$parentID&depth=1"); 
        ?>
    </ul>
<?php endif; ?>

Put this into your functions.php file, it’s a function that will return our top most page ID.

/** Get Top Most Page ID and Return it **/
function get_ancestor(){
    global $post;
    $id = 0;

    if(is_object($post)){
        $id = $post->ID;

        if($post->post_parent){
            $ancestors = get_post_ancestors($post->ID);
            $root = count($ancestors)-1;
            $id = $ancestors[$root];
        }
    } 
    else if(is_singular('post') || is_archive() || (is_home() && !is_front_page())){
        $id = get_option('page_for_posts');
    }

    return $id;
}

Leave a Comment