Test if page is child and has children, if so echo child pages also on grandchild pages

I am trying to show a sub-menu of child-pages only on level 2 pages (who have a parent) and if they have children. I am using the code below (made from several snippets I found), it works fine on level 1 (not showing anything as meant to be), works fine on level 2: if there are child pages they are shown in the sub-menu.

My question: When i go to level 3 pages I would like the sub-menu to stay but it disappears. How can I change the code below to make it work?

    <?php 
        if (is_page() && $post->post_parent ) { // test to see if the page has a parent

          $page = $post->ID;

          if (is_page() ) {
            $page = $post->post_parent;
          }

          $children=wp_list_pages( 'echo=0&child_of=' . $page . '&title_li=' );


          if ($children) {
            $output = wp_list_pages( array(
                'child_of' => $post->ID, // Only pages that are children of the current page
                'depth' => 1, // Only show one level of hierarchy
                'title_li' => ''
            ) );
          }


        } 

echo $output; 

?>

Related posts

1 comment

  1. Use ancestors:

    $ancestors = array_reverse( get_post_ancestors( $post->ID ) ); // reverse ancestors to make it more intuitive
    
    if ( isset( $ancestors[0] ) ) {
    
        if ( isset( $ancestors[1] ) ) {
            // 3rd tier
            $parent_id = $post->post_parent;
        } else {
            // 2nd tier
            $parent_id = $post->ID;
        }
    
        $args = array(
            'depth' => 1,
            'child_of' => $parent_id,
        );
    
        wp_list_pages( $args );
    }
    

Comments are closed.