A WordPress function should return the top level term id of a given child term id - terms can have 1..n parents, so a recursive function seems to be useful here.
// Recursive function
function return_top_level_term($term_id, $taxonomy_name) {
$term = get_term_by('id', $term_id, $taxonomy_name);
if($term->parent>0) {
return_top_level_term($term->parent, $taxonomy_name);
} else {
// Here we get the correct value
return $term->term_id;
}
}
PHP indeed does find the correct term_id, but the function always returns false.
$my_top_level_term = return_top_level_function(423, $tax);
Example with three layers, informal notation:
return_top_level_term(return_top_level_term(return_top_level_term(return 1;)return false;) return false;)
I am searching for the 1, but false is always returned, although the the function does not have a return value.
Of course I could write a local variable above the function which can save the value because of the scope rules, but I want to write it into a library - is there a way of returning this value by calling the recursive function?