<?php
/**
* Retrieve a post\'s terms as a list ordered by hierarchy.
*
* @param int $post_id Post ID.
* @param string $taxonomy Taxonomy name.
* @param string $term_divider Optional. Separate items using this.
* @param string $reverse Optional. Reverse order of links in string.
* @return string
*/
class GetTheTermList {
public function get_the_term_list($post_id, $taxonomy, $term_divider = \'/\', $reverse = false) {
$object_terms = wp_get_object_terms($post_id, $taxonomy);
$parents_assembled_array = array();
//***
if (!empty($object_terms)) {
foreach ($object_terms as $term) {
$parents_assembled_array[$term->parent][] = $term;
}
}
//***
$sorting_array = $this->sort_taxonomies_by_parents($parents_assembled_array);
$term_list = $this->get_the_term_list_links($taxonomy, $sorting_array);
if ($reverse) {
$term_list = array_reverse($term_list);
}
$result = implode($term_divider, $term_list);
return $result;
}
private function sort_taxonomies_by_parents($data, $parent_id = 0) {
if (isset($data[$parent_id])) {
if (!empty($data[$parent_id])) {
foreach ($data[$parent_id] as $key => $taxonomy_object) {
if (isset($data[$taxonomy_object->term_id])) {
$data[$parent_id][$key]->childs = $this->sort_taxonomies_by_parents($data, $taxonomy_object->term_id);
}
}
return $data[$parent_id];
}
}
return array();
}
//only for taxonomies. returns array of term links
private function get_the_term_list_links($taxonomy, $data, $result = array()) {
if (!empty($data)) {
foreach ($data as $term) {
$result[] = \'<a rel="tag" href="\' . get_term_link($term->slug, $taxonomy) . \'">\' . $term->name . \'</a>\';
if (!empty($term->childs)) {
//***
$res = $this->get_the_term_list_links($taxonomy, $term->childs, array());
if (!empty($res)) {
//***
foreach ($res as $val) {
if (!is_array($val)) {
$result[] = $val;
}
}
//***
}
//***
}
}
}
return $result;
}
}
?>
<?php
//EXAMPLE OF USING
$term_list_object = new GetTheTermList();
$car_location = $term_list_object->get_the_term_list($post_id, \'carlocation\', \'-\',TRUE);
?>