WordPress.org

Ready to get started?Download WordPress

Forums

Hierarchical display of Pages (or: how to nest calls to `new WP_Query`) (3 posts)

  1. aksleet
    Member
    Posted 3 years ago #

    Hello,

    I am trying to provide a WordPress website for a small commercial customer. I would like their site to display a navigation menu where all pages are displayed hierarchically. To this effect, I am attempting to use nested WP_Query's; one top-level query to get the top-level pages, and second-level queries to get the children of a particular top-level page. My code is:


    <?php
    $pages = new WP_Query(array('post_type' => 'page'));
    while ($pages->have_posts())
    {
    $pages->the_post(); // advance the query enumerator
    $page = $post;

    if (!($page->post_parent)) // Only act on top-level pages
    {
    ?>
    <!-- HTML for parent -->
    <?php
    $children = new WP_Query(array('post_type' => 'page', 'post_parent' => $page->ID));
    while ($children->have_posts())
    {
    $children->the_post(); // advance the query enumerator
    $child = $post;
    ?>
    <!-- HTML for child -->
    <?php
    }
    }
    }
    wp_reset_postdata(); // Reset the_loop since our calls to WP_Query->the_post() overwrote the global the_loop
    ?>

    The code iterates once through the outer while-loop (incidentally it picks up the "Home" page, which has no children, so the inner loop is not executed) and then when it begins a second iteration of the outer loop, I get this error:

    Fatal error: Call to a member function have_posts() on a non-object in /Users/me/Sites/customer/wordpress/wp-content/themes/customer/index.php on line XX

    Line XX corresponds to while ($pages->have_posts()) in my code.

    1) is there an easier way to get a hierarchy of the pages? 2) What am I doing wrong with my queries/the_loop? Thank you very much.

  2. aksleet
    Member
    Posted 3 years ago #

    Also, this code appears in my index.php; that is the only template I am providing since the website is small and not blog/comment-oriented.

  3. aksleet
    Member
    Posted 3 years ago #

    I should also mention that wp_list_pages does not work for me because I need to control the HTML that is output for each of the pages.

Topic Closed

This topic has been closed to new replies.

About this Topic