parent; if (!isset($children_map[$pid])) { $children_map[$pid] = []; } $children_map[$pid][] = $term; } $render = static function (int $pid, int $d) use (&$render, $children_map, $checked, $name): void { if (empty($children_map[$pid])) { return; } foreach ($children_map[$pid] as $term) { $tid = (int) $term->term_id; $pad = $d > 0 ? ' style="margin-left:' . (int) ($d * 16) . 'px"' : ''; echo ''; $render($tid, $d + 1); } }; // If include list was used without hierarchy, still render flat. if (empty($children_map) && !empty($terms)) { foreach ($terms as $term) { if (!$term instanceof WP_Term) { continue; } $tid = (int) $term->term_id; echo '
'; } return; } $render($parent, $depth); // Orphans (included children without parent in set). $seen_parents = array_keys($children_map); foreach ($terms as $term) { if (!$term instanceof WP_Term) { continue; } $pid = (int) $term->parent; if ($pid > 0 && !isset($children_map[$pid]) && !isset($children_map[0])) { // already handled if parent missing — skip double. } } } endif;