Only the first and last term is added, all others are omitted in your code. A street is created twice, because you double-insert the last element of the array.
else if ($i == $len - 1) {
wp_insert_term( $term, 'location', array( 'parent'=> $term_id ) );
// Child terms
wp_insert_term( $term, 'location' );
}
Try to change foreach
loop:
$location_array_reversed = array_reverse( $location_array );
$parent_id = 0;
$location_array_ids = [];
$taxonomy_slug = 'location';
foreach( $location_array_reversed as $term ) {
$res = term_exists( $term, $taxonomy_slug, $parent_id );
if ( $res === NULL || $res == 0 )
$res = wp_insert_term( $term, $taxonomy_slug, ['parent' => $parent_id] );
$term_id = (int) $res['term_id']; // ID of existing or inserted term
// Save term ID to array
$location_array_ids[] = $term_id;
$parent_id = $term_id;
}
wp_set_object_terms($post_id, $location_array_ids, $taxonomy_slug);
wp_insert_term()
returns ID of the inserted term, so you don’t need to use get_term_by()
to get ID of the inserted element.