0

I have a Page layout like this

Parent Page
- Sub page 1
-- sub sub 1
-- sub sub 2
-- sub sub 4
- Sub page 2
-- sub sub 1
-- sub sub 2
-- sub sub 4

I want to query every single child page, regardless of how deep I go. This is my query but it only returns direct children(sub page 1 and 2)

query_posts('post_type=page&order=ASC&orderby=menu_order&depth=4&post_parent='.$post->ID);

How can I do this?

  • 1
    The inner posts don't have a parent of $post->ID but instead on subpages you need to query again using that $post->ID as the parent. – Kevin Langley Jr. Nov 8 '11 at 19:09
1

I'm pretty sure you can use get_pages (http://codex.wordpress.org/Function_Reference/get_pages) function to solve this. It has child_of parameter which does exactly what you wanted.

The only problem is that it returns posts and not set $wp_query, so you can't use it as loop, but you can always call setup_postdata and then use template tags as in normal posts loop.

<?php
    $mypages = get_pages( array( 'child_of' => <PARENT_PAGE_ID>) );
    foreach( $mypages as $page ):
?>
        <h2><a href="<?php echo get_page_link( $page->ID ); ?>"><?php echo apply_filters('the_title', $page->post_title); ?></a></h2>
        <div class="entry"><?php echo apply_filters( 'the_content', $page->post_content ); ?></div>
<?php endforeach; ?>
-1

try this

function wpse33151_getSubpages() {      
    global $post;

    $parents = get_post_ancestors($post->post_id);
    krsort($parents);
    $parents = array_merge(array(), $parents);

    if (is_home() || is_single()) {
        $id = get_option('page_for_posts');
        $parent = get_post_ancestors($id);
        $id = $parent[0];
    } elseif($parents) {
        $id = $parents[0];
    } else {
        $id = $post->ID;
    }

    $children = wp_list_pages('title_li=&child_of=' . $id . '&echo=0');
    $out = null;

    if ($children) {
        $out = '';
        $out .= '' . get_the_title($id) . '';
        $out .= '
    '; $out .= $children; $out .= '
'; $out .= ''; } return $out; }
  • From which source did you paste this? $parents = array_merge(array(), $parents); is merging an array with an empty array. For what reason? Also: $out .= '' . get_the_title($id) . ''; places a function between 2 times nothing :) – kaiser Feb 26 '12 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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