I am successfully listing posts grouped by category from a custom taxonomy like so:
Category 1
- Post
- Post
- Post
Category 2
- Post
- Post
- Post
Category 3
- Post
- Post
- Post
Category 4
- Post
- Post
- Post
I am trying to only list groups of categories (with their posts) that are descendants of parent categories. For example, if Category 1 is the parent of Category 2 and Category 3 is the parent of Category 4, I only want to list:
Category 2
- Post
- Post
- Post
Category 4
- Post
- Post
- Post
The code I already have lists all posts grouped by all categories, parent or children:
$taxonomy = 'diorganosi';
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
$tax_terms = get_terms( $taxonomy,
array(
'parent' => $term_id,
'hide_empty' => true, // change to true if you don't want empty terms
'orderby' => 'name',
'order' => 'DESC',
'fields' => 'names', // return the term names only
)
);
foreach($tax_terms as $tax_term) { // loop through the terms
echo '<h2>' . $tax_term . '</h2>'; // echo the term name as a h2
$term_posts = get_posts( // find posts with the correct term
array(
'no_found_rows' => true, // for performance
'ignore_sticky_posts' => true, // for performance
'post_type' => 'prognostika',
'posts_per_page' => -1, // return all results
'tax_query' => array( // https://developer.wordpress.org/reference/classes/wp_tax_query/
array(
'taxonomy' => $taxonomy,
'field' => 'name',
'terms' => array( $tax_term )
)
),
'fields' => 'ids', // return the post IDs only
)
);
echo '<ul>'; // open bullet list
foreach($term_posts as $term_post_id) { // loop through posts
$post_title = get_the_title($term_post_id); // get post title
$post_permalink = get_the_permalink($term_post_id); // get post link
echo '<li>'; // open list item
echo '<a href="' . $post_permalink . '">' . $post_title . '</a>'; // add link to post with post title as link text
echo '</li>'; // close list item
}
echo '</ul>'; // close bullet list
}
As you can see, I tried adding:
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
then referencing 'parent' => $term_id
inside get_terms
but no luck.