0

I registered a custom post type drawer where my posts are ordered using menu_order. Each drawer could be a child of another drawer, on a multiple depth (parent > child > child of child > child of child of child...... you get the idea ;)).

My code so far looks like that :

$args = array(
    'numberposts'     => -1,
    'orderby'         => 'menu_order',
    'order'           => 'DESC',
    'post_type'       => 'drawer',
    'post_status'     => 'publish',
);
$drawers = get_posts($args);

foreach ($drawers as $drawer){
    $title = get_the_title($drawer->ID);
    echo $title . ' (parent : ' . $drawer->post_parent . ')<br>';
}

But I'd like to get the child of a parent post right after the parent post is returned, with the menu_order value being used to sort these children too.

I get the whole logic : I should somehow create a "nested" loop where I use get_posts with the parent parameter set to verify & get the sorted children. But because I can have a lot of depth with this parent/child behaviour, I don't think that's the most efficient way and I can't get my mind to create a "nested" loop.

To visualize what I need : look at this image http://img.saika.li/Opkq to understand the real order that I'd like to get (blue titles) compared to what I get for now.

I hope someone has a solution !

1 Answer 1

0

The problem with grasping implementation for such deeply nested tree is that it is best solved recursively - your code should output post, then output children and endlessly repeat the process for each child until it runs out.

However before you spend time on custom implementation you could try to look into existing functions WP provides. For example wp_list_pages() can really be used for arbitrary post type and should handle hierarchical output for you.

2
  • Thx @Rarst, that did the trick. I created a custom walker to handle the output. Weirdly, there is a 'sort_column' parameter but no 'sort_order' (ASC/DESC), so it's ascending by default. I'll try to figure out the correct filter to change that. Anyway, big thanks ! Commented May 8, 2013 at 20:00
  • Sorry I'm quite wrong, you can use 'sort_column' => 'menu_order' coupled with 'sort_order' => 'DESC' ! Commented May 8, 2013 at 20:04

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