1

I have a hierarchical custom post type, and on each single view of a post of this type I want to display the title of the children of this post, outside of the loop.

The code I'm currently using is below, and it works - but I've no idea whether it's a sensible way to do it or if there's other options.

$pageChildren = get_pages('child_of='.$post->ID."&echo=0&post_type=show");
if ( $pageChildren ) {
    foreach ( $pageChildren as $pageChild ) {
        echo '<p><a href="' . get_permalink($pageChild->ID) . '">'. $pageChild->post_title.'</a></p>';
    }
}
9
  • Looks fine to me.
    – cjbj
    Jun 8, 2016 at 15:49
  • What if a child of child is there ?
    – Sumit
    Jun 8, 2016 at 16:06
  • @cjbj - thanks, that's encouraging; it's code I found elsewhere.
    – gulliver
    Jun 9, 2016 at 5:43
  • @Sumit - thanks, I hadn't thought of that; do you have suggestions please?
    – gulliver
    Jun 9, 2016 at 5:43
  • You can use wp_list_pages()!
    – Sumit
    Jun 9, 2016 at 17:49

1 Answer 1

0

wp_list_pages calls get_pages internally and pass the argument list to get_pages so you can pass arguments whatever get_pages accept.

To display child posts on your single-{post_type}.php you need to call wp_list_pages with post_type parameter.

wp_list_pages will ignore post_type but it will pass this to get_pages.

Example:-

echo '<ul>';

wp_list_pages(array(
    'post_type' => 'show',
    'child_of' => get_the_ID(),
    'title_li' => false //Set to false to disable the heading
));

echo '</ul>';

The only benefit of using wp_list_pages is hierarchical display in case if you have grandchildren of a post. get_pages with foreach loop will always give you flat list regardless of child or grandchild.

1
  • thanks, appreciated. I'm beginning to understand this stuff much better now.
    – gulliver
    Jun 14, 2016 at 5:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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