二级分类
<?php
function get_immediate_child_terms($term_id, $taxonomy) {
return get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => $term_id,
'orderby' => 'name', // Optional: order alphabetically
'order' => 'ASC'
]);
}
// In taxonomy.php
$current_term = get_queried_object();
$level_2_terms = get_immediate_child_terms($current_term->term_id, $current_term->taxonomy);
// More detailed rendering
if (!empty($level_2_terms)) {
echo '<div class="taxonomy-children">';
foreach ($level_2_terms as $term) {
// Additional term details
echo '<div class="term-item">';
echo '<h4><a href="' . get_term_link($term) . '">' . $term->name . '</a></h4>';
echo '<p>Posts in this category: ' . $term->count . '</p>';
echo '</div>';
}
echo '</div>';
}
?>
三级分类
<?php
function get_nested_child_terms($term_id, $taxonomy, $current_depth = 1, $max_depth = 3) {
if ($current_depth > $max_depth) return [];
$child_terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => true,
'parent' => $term_id,
]);
$nested_terms = [];
foreach ($child_terms as $child_term) {
$child_term->children = get_nested_child_terms(
$child_term->term_id,
$taxonomy,
$current_depth + 1,
$max_depth
);
$nested_terms[] = $child_term;
}
return $nested_terms;
}
// Usage in taxonomy.php
$current_term = get_queried_object();
$level_3_terms = get_nested_child_terms($current_term->term_id, $current_term->taxonomy);