You can use get_term_children()
to check if a specific term has any children, and if yes, display the children; otherwise, display the parent”s children.
So just change the if ($term->parent == 0) {
to:
$children = get_term_children( $term->term_id, $term->taxonomy );
if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
Or here’s the full code I used:
$term = get_queried_object();
$children = get_term_children( $term->term_id, $term->taxonomy );
if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
wp_list_categories( 'taxonomy=' . $term->taxonomy . '&depth=1&show_count=0&title_li=&child_of=" . $term->term_id );
} else {
wp_list_categories( "taxonomy=' . $term->taxonomy . '&depth=1&show_count=0&title_li=&child_of=" . $term->parent );
}