I am trying to loop through the category
taxonomy and display the posts attached to each term
, with a heading (the term name) separating each term's posts (and also display all the terms, even those that are not attached to any posts).
Additionally, I need the child terms to be displayed as subheadings under their parent term's heading.
For example:
- AUTOMOTIVE (top-level/parent term w/ no children)
- Post 1
- Post 2
- BUILDING SUPPLY (parent term)
- Drywall (child term)
- Post 3
- Post 4
- Drywall (child term)
After hours of reading and trial & error I have this code working to display just the top-level, parent terms first. I'm hoping a Wordpress ninja can make my day and guide me where to go now:
<?php
$taxonomy = 'category'; // Choose the taxonomy
// Get all the terms
$terms = get_terms( $taxonomy, array(
'hide_empty' => false,) // Show terms with no posts attached
);
foreach ($terms as $term) { // Cycle through terms, one at a time
// Check and see if the term is a top-level parent - if so, display it
$parent = $term->parent;
if ( $parent=='0' ) {
echo '<h2>' . $term->name . '</h2>';
***Need to loop term posts here, with headings for child terms***
}
}
?>