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.

I want to add a ul to the list when a page have a child, Im making a foreach on all the post_types so i don't think that i can use something like wp_list_pages. I have been trying to sort this out but just ended upp with this:

// Check for children
$children = array(); 
foreach ( $values as $post ) {
  if( $post->post_parent ) {
    $children[] = $post->ID;
  }
}
foreach ( $values as $post ) {
  setup_postdata( $post );
     if( in_array( $post->ID, $children ) ) {
        $output .= '<ul>';
           $output .= '<li data-id="'. $post->ID .'" data-area="'. $area['area'] .'"><p>'. get_the_title() .'</p><span>'. __('Child', 'blocks') .'</span></li>';
        $output .= '</ul>';
     } else {
        $output .= '<li data-id="'. $post->ID .'" data-area="'. $area['area'] .'"><p>'. get_the_title() .'</p><span>'. __('Parent', 'blocks') .'</span></li>';
     }  
  wp_reset_postdata();                              
}
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted
//first let's separate all the top level pages & child pages
$top_lvl = array();
$children = array();
foreach ( $values as $post ) {
  if( $post->post_parent ) {
    $children[$post->post_parent][] = $post;
  } else {
    $top_lvl[] = $post;
  }
}

//now we have all top level pages in $top_lvl
//& we can access their child pages at $children[<top_lvl_ID>]
//now lets loop through top_lvl pages & display them
foreach ( $top_lvl as $post ) {
  setup_postdata( $post );
  $output .= '<li data-id="'. $post->ID .'" data-area="'. $area['area'] .'"><p>'. get_the_title() .'</p><span>'. __('Parent', 'blocks') .'</span></li>';
  //check if this post has children
  if( isset( $children[$post->ID] ) ) {
    foreach( $children[$post->ID] as $post ) {
      //do something with children here
    }
  }
}
//can't forget to reset the global data
wp_reset_postdata();
share|improve this answer
    
Thanks @Mridul, But the soulution dosent work the whole way.. I want it do be: <ul> <li>Parent</li> <ul> <li>Child</li> <li>Child</li> <li>Child</li> </ul> </ul> Now i only get Undefined offset: on foreach( $children[$post->ID as $post]) –  Pontus Abrahamsson Dec 17 '12 at 15:53
    
Okey i sorted it out now, Your code worked great. But i had some old pages and they needed to be saved again.. weird. Thanks –  Pontus Abrahamsson Dec 17 '12 at 17:01
    
The error was here- foreach( $children[$post->ID as $post]) should be foreach( $children[$post->ID] as $post) –  Mridul Aggarwal Dec 17 '12 at 18:38
add comment

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.