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.

So here's what I'm trying to do: I'm trying to develop a theme that shows any sub-pages on the parent page. I've gotten this running successfully with a WP_query and a simple loop:

<!--show sub pages on this page-->
<?php $childargs = array( 'post_parent' => $post->ID, 'post_type' => 'page', 'posts_per_page' => '-1', 'orderby' => 'menu_order', 'order' => 'ASC' );      
$child = new WP_Query($childargs);

// only show the navbar on pages with sub-children
if ($child->have_posts()) { ?>
    <div class="sub">
    <div class="pw">
        <?php if ($child->have_posts()) : while ($child->have_posts()) : $child->the_post(); ?>
            <a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
        <?php endwhile; endif;

        wp_reset_query(); ?>
    </div>
    </div><!--sub-->
<?php } ?>

This code displays absolutely nothing on the child pages themselves, which is the correct behavior. I want the child pages show this nav, but I don't know how to do that. $childargs references the postid, which in the case of the child page will be the child page (which has no children of its own).

How can I modify this code so that it not only displays on parent pages, but on child pages as well? A demo page can be found here: http://sheepish-lab637.com/one/about/ with sub-children of its own.

Edit: perhaps this could be better accomplished by a Wordpress menu, which would also have the advantage of bundling the default current_page_item classes and such.

Thanks!

share|improve this question
    
I'm wondering if I can manipulate WP_query to get the child pages of a child page's parent. . . –  authorandrew Sep 3 at 17:29

1 Answer 1

up vote 1 down vote accepted

If it's a child page, the post_parent will be a non-zero value, so you could check for that:

if( 0 == $post->post_parent ){
    // no parent, get children of this page
    $childargs['post_parent'] = $post->ID;
} else {
    // has parent, get children of parent page
    $childargs['post_parent'] = $post->post_parent;
}

This is assuming your child pages are just a single level below the parent pages. Otherwise, you can fetch all the ancestors of a page with get_post_ancestors, and get the ID of the highest level parent:

$parents = get_post_ancestors( $post->ID );
$top_level_page = $parents[ count($parents) - 1 ];
share|improve this answer
    
Works perfectly, many thanks! –  authorandrew Sep 3 at 20:39

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.