steve
steve

Reputation: 688

How to get each parent page, and display its children as separate divs in Wordpress

Right now I have the following PHP:

<?php
$pages = get_pages( array( 'sort_column'=>'menu_order', 'parent'=>'0') );
    foreach ($pages as $page_data) {
      $content = apply_filters('the_content', $page_data->post_content);
      $title = $page_data->post_title;
      $slug = $page_data->post_name;
      $pageid=$page_data->ID;

        echo '<div class="section'.(($title=='intro')?' intro-section':"").'">';
        echo $content;
        echo "</div>";
    }
?>

There are 5 Pages, 2 of which have many child Pages. I want to take the above code further one level, so that each page will have its own wrapper, and, if a Page has children Pages, those pages will be placed within the same .section, but each within a separate div. Any advice? I'm a bit inexperienced in Wordpress so any help would be great. Below should give an example of what I want:

<div class="section">
    <div class="page parent"></div>
</div>
<div class="section">
    <div class="page parent"></div>
    <div class="page child"></div>
    <div class="page child"></div>
</div>
<div class="section">
    <div class="page parent"></div>
</div>

Below is the code I'm working with right now.

<?php while (have_posts()) : the_post(); ?>
<?php
$pages = get_pages( array( 'sort_column'=>'menu_order', 'parent'=>'0') );
    foreach ($pages as $page_data) {
      $content = apply_filters('the_content', $page_data->post_content);
      $title = $page_data->post_title;
      $slug = $page_data->post_name;
      $pageid=$page_data->ID;

        //Put a container around every page's content
      if (count(get_pages('child_of=' . $page_data->ID.''))) {
            // Loop through $page_data array to print the div you want 
        echo '<div class="section">';
        echo '<div class="slide">';
        echo $content;
        echo "</div>";

       $children = get_pages('child_of=' . $page_data->ID.'');
      foreach( $children as $child ) {
        $childcontent = apply_filters('the_content', $child->post_content);
        echo '<div class="slide">';
        echo $childcontent;
        echo "</div>";
      }
      echo "</div><!--end section-->";
      } else {

        echo '<div class="section'.(($title=='intro')?' intro-section':"").'">';
        echo $content;
        echo "</div>";
    }
  }
?>
<?php endwhile ?>

Upvotes: 0

Views: 719

Answers (1)

Zameer Khan
Zameer Khan

Reputation: 1196

Use child_of parameter of get_pages() function inside the loop. This parameter lists the sub-pages of a single Page only. It uses the ID for a Page as the value.

Eg.

if (count(get_pages('child_of=' . $page_data->ID))) {
    // Loop through $page_data array to print the div you want 
}

Upvotes: 3

Related Questions