I want to display the WooCommerce sub-categories based on the current categorie ID.
To get all sub-categories, I’m using the following code to get all child IDs. The problem is, that I get all levels below the current category.
Is there any way to limit the categories to only the next level? For example: Level 1 only gets categegories from leven 2 and level 2 only from level 3.
Here’s my code (it’s from the WordPress docs):
$term_id = $productcat_id; $taxonomy_name = 'product_cat'; $termchildren = get_term_children( $term_id, $taxonomy_name ); echo '<ul>'; foreach ( $termchildren as $child ) { $term = get_term_by( 'id', $child, $taxonomy_name ); echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>'; } echo '</ul>';
Advertisement
Answer
As taken from https://wordpress.stackexchange.com/a/124429
You could do
$term_children = get_terms( 'product_cat', array( 'parent' => get_queried_object_id(), ) ); if ( ! is_wp_error( $terms ) ) { echo '<ul>'; foreach ( $termchildren as $child ) { $term = get_term_by( 'id', $child, $taxonomy_name ); echo '<li><a href="' . get_term_link( $child ) . '">' . $child->name . '</a></li>'; } echo '</ul>'; }