Đôi khi có những trường hợp cần thiết để có được các liên kết phân loại của bài đăng được xếp hạng trong hệ thống phân cấp. WordPress có chức năng nhận các liên kết phân loại tùy chỉnh bài viết:
1 | <?php get_the_term_list($id, $taxonomy, $before, $sep, $after) ?> |
Nhưng: bạn không thể nhận được nó theo phân cấp! Tôi đã có một nhiệm vụ như vậy. Và tôi muốn mô tả quyết định của tôi về nhiệm vụ này.
Tôi đã viết một lớp học nhỏ:
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; } } ?> |
Sử dụng lớp php này rất đơn giản:
Ví dụ:
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); ?> |
Lớp php này dùng để thay thế hàm WordPress get_the_term_list khi điều quan trọng là phải sắp xếp theo thứ bậc các liên kết điều khoản phân loại của một bài đăng.