Skip to content

Instantly share code, notes, and snippets.

@avenirer
Last active June 27, 2019 08:03
Show Gist options
  • Save avenirer/874531d3ce5ab03655a360dd6f145e05 to your computer and use it in GitHub Desktop.
Save avenirer/874531d3ce5ab03655a360dd6f145e05 to your computer and use it in GitHub Desktop.
Wordpress - get hierarchical parents of a taxonomy term
<?php
/**
* Retrieve an array of taxonomy terms that represent the parents of the given term
*
* @param $term_obj_or_id
* @param $taxonomy
* @param array $hierarchy
*
* @return array
*/
function get_term_hierarchical_parents($term_obj_or_id, $taxonomy, $hierarchy = array() ) {
if (is_numeric($term_obj_or_id)) {
$term_obj = get_term($term_obj_or_id,$taxonomy);
}
else {
$term_obj = $term_obj_or_id;
}
if ( empty($hierarchy)) {
$hierarchy = array($term_obj);
}
if($hierarchy[0]->parent != 0) {
$parent_term = get_term($hierarchy[0]->parent, $taxonomy);
if ( $parent_term instanceof WP_Term) {
array_unshift($hierarchy, $parent_term);
}
return get_term_hierarchical_parents($parent_term,$taxonomy, $hierarchy);
}
else {
return $hierarchy;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment