I have a hierarchal custom post type called “courses”.
When you arrive on a course post there’s a check to see if the post has children. If the courses post has children it runs get_posts to display a list of those children.
Here’s where I’m struggling; part of the detail of a child list item is to display the number of children that child post has. So what I’ve tried to do is run a get_posts within a get_posts, but this is not working as expected.
To put things in context, and perhaps explain things better, here’s some of the hierarchy:
- Adobe > Acrobat > Introductory Course
- Adobe > FrameMaker > Advanced Course
- Adobe > FrameMaker > Introductory Course
So when a visitor clicks on “Adobe” they get a list of the children, two items:
- Acrobat; &
- Framemaker.
Underneath these titles should be detail of how many sub-courses are available, so Acrobat should say; “1 course available” and Framemaker should say “2 courses available”.
This doesn't work. The sub get_posts
returns nothing. My specific question is; how do I find out how many children a child has when inside a get_posts
loop. Or should I try a different approach?
My current (simplified) code...
$postid = get_the_ID();
$kids = array(
'post_type' => 'courses',
'post_parent' => $postid
);
$children = get_posts( $kids );
if ( $children ) {
echo '<ul>';
foreach( $children as $child ) {
$childid = $child->ID;
$coursetitle = get_the_title( $childid );
$grandkids = get_posts( array(
'post_type' => 'courses',
'post_parent' => $childid
) );
$grandchildren = count($grandkids);
echo '<li>';
echo $coursetitle;
echo $grandchildren . 'courses available';
echo '</li>';
}
}
Any help from you wise ones would be much appreciated.
get_terms
to retrieve an array of children of a specific term (in your case "Adobe"). Then take the length of that array.post_type
, so it defaults topost
.Adobe
posts, or are they terms