get_pages – Display child then grandchild pages

You don’t need 2 queries, just use a bit of logic and 2 foreach loops:

$portfolioID = $post->ID;

$portfolio_sections = array(
  'post_type' => 'page',
  'child_of' => $portfolioID,
  'sort_column' => 'menu_order',
  'sort_order' => 'ASC',
);

$sections = get_pages($portfolio_sections);

$hierachical = array();

if ( ! empty($sections) ) {
  foreach ( $sections as $section ) {
    if ( $section->post_parent == $portfolioID ) {
      if ( ! isset( $hierachical[$section->ID]) ) $hierachical[$section->ID] = array();  
      $hierachical[$section->ID]['child'] = $section;
      $hierachical[$section->ID]['grandchildes'] = array();
    } else {
      if ( ! isset( $hierachical[$section->post_parent]) ) $hierachical[$section->post_parent] = array();
      $hierachical[$section->post_parent]['grandchildes'][] = $section;
    }
  }
  foreach ( $hierachical as $id => $hierachical_data ) {
    if ( ! isset($hierachical_data['child']) || ! is_object($hierachical_data['child']) ) continue;
    echo '<div class="grid">';
    echo '<h2>' . get_the_title($hierachical_data['child']->ID) . '</h2>';
    echo '<ul>';
    if ( isset($hierachical_data['grandchildes']) && ! empty($hierachical_data['grandchildes']) ) {
      foreach ( $hierachical_data['grandchildes'] as $grandchild ) {
        if ( has_post_thumbnail($grandchild->ID)) {
          echo '<li><a href="' . get_permalink( $grandchild->ID ) . '" title="' . esc_attr( $grandchild->post_title ) . '">';
          echo get_the_post_thumbnail($grandchild->ID);
          echo '</a></li>';
        }
      }
    }
    echo '</ul>';
    echo '</div>';
  }
}

Code untested but should works.

Leave a Comment