Sometimes there are cases when its necessary to get taxonomies links of post ranked in the hierarchy. WordPress has the function to get posts custom taxonomies links:
1 | <?php get_the_term_list($id, $taxonomy, $before, $sep, $after) ?> |
But: you cant get it by hierarchy! I had such a task. And I want to describe my decision of this task.
I wrote a little class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | <?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 href="' . get_term_link($term->slug, $taxonomy) . '" rel="tag">' . $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; } } ?> |
Using of this php class is simple:
Example:
1 2 3 4 5 6 | <?php //SORTING TERMS OF CARS $term_list_object = new GetTheTermList(); $data['car_location'] = $term_list_object->get_the_term_list($post_id, 'carlocation', $term_divider); $data['car_producer'] = $term_list_object->get_the_term_list($post_id, 'carproducer', $term_divider); ?> |
This php class is for replace WordPress function get_the_term_list when it is important to get ordered by hierarchy taxonomies terms links of a post.
