Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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; 

?>
share|improve this question
    
I am a little confused what you mean by retrieving list into $children variable only to use it for check and discard? –  Rarst May 7 '13 at 20:26

1 Answer 1

up vote 2 down vote accepted

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 );
}
share|improve this answer
    
Hi vancoder, Thanks a lot for the answer, it's working like a charm! –  xarai May 8 '13 at 9:47
    
Good - please mark it as correct (click the tick) so that other people with the same issue can see it is correct. –  vancoder May 8 '13 at 16:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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