I've created a function that generates an <ul>
of my wordpress custom taxonomy terms, displaying parent > child > second child
heirachy. Functionally it is working perfectly and replaces my old hard-coded menu.
The problem is I'm inexperienced and recognise it as an ugly, inefficient function but could not figure out how to make it better. I tried use 'While()' loops to simplify things but came unstuck. Could someone help me understand how to improve this. The final output (including CSS and jQuery to collapse deactivated menu items) is included below.
//Display Navigation Menu
function taxonomy_nav(){
//Get Parent Terms
$getParents = [
'taxonomy' => 'kernal_category',
'parent' => 0,
'number' => 0,
'hide_empty' => false
];
//Assign parent terms to variable
$parent_terms = get_terms( $getParents );
//Loop through parent terms
foreach ( $parent_terms as $parent_term ) {
//Store children terms
$childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );
//If parent term has children...
if ( ! is_wp_error( $childrenCheck ) && ! empty ( $childrenCheck ) ) {
//Output parent term and start new children list
echo '<li><a href="'. get_term_link( $parent_term ) .'">'. $parent_term->name.'</a>';
echo '<ul>';
//Loop through child items and output name
foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term) {
//Check if children have children
$secondChildrenCheck = get_term_children( $child_term->term_id, $child_term->taxonomy );
//Generate list for second children
if ( ! is_wp_error( $secondChildrenCheck ) && ! empty( $secondChildrenCheck ) ) {
echo '<li><a href="' . get_term_link( $child_term ) . '">' . $child_term->name.'</a>';
echo '<ul>';
//If child has child, look through child
foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $child_term->term_id ) ) as $second_child_term) {
echo '<li><a href="'. get_term_link( $second_child_term ) . '">'.$second_child_term->name . '</a></li>';
}
echo '</ul>';
echo '</li>';
} else {
echo '<li><a href="'. get_term_link( $child_term ) .'">'. $child_term->name.'</a></li>';
}
}
echo '</ul>';
echo '</li>';
} else {
echo '<li><a href="'. get_term_link( $parent_term ) .'">'. $parent_term->name.'</a></li>';
}
}