terms – List posts grouped by children of a custom taxonomy

Question

I am successfully listing posts grouped by category from a custom taxonomy like so:

Category 1

Category 2

Category 3

Category 4

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

Category 4

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.

0
quantum_leap 7 months 2022-11-19T17:16:33-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse