1 | <?php |
---|
2 | /** |
---|
3 | * Retrieves term parents with separator. |
---|
4 | * |
---|
5 | * @since 4.8.0 |
---|
6 | * |
---|
7 | * @param int $term_id Term ID. |
---|
8 | * @param string $taxonomy Taxonomy name. |
---|
9 | * @param string|array $args { |
---|
10 | * Array of optional arguments. |
---|
11 | * |
---|
12 | * @type string $format Use term names or slugs for display. Accepts 'name' or 'slug'. |
---|
13 | * Default 'name'. |
---|
14 | * @type string $separator Separator for between the terms. Default '/'. |
---|
15 | * @type bool $link Whether to format as a link. Default true. |
---|
16 | * @type bool $inclusive Include the term to get the parents for. Default true. |
---|
17 | * @type bool $reverse Wether to reverse the hierarchical order of the Terms on output. Default true. |
---|
18 | * } |
---|
19 | * @return string|WP_Error A list of term parents on success, WP_Error or empty string on failure. |
---|
20 | */ |
---|
21 | function get_term_parents_list( $term_id, $taxonomy, $args = array() ) { |
---|
22 | $list = ''; |
---|
23 | $term = get_term( $term_id, $taxonomy ); |
---|
24 | |
---|
25 | if ( is_wp_error( $term ) ) { |
---|
26 | return $term; |
---|
27 | } |
---|
28 | |
---|
29 | if ( ! $term ) { |
---|
30 | return $list; |
---|
31 | } |
---|
32 | |
---|
33 | $term_id = $term->term_id; |
---|
34 | |
---|
35 | $defaults = array( |
---|
36 | 'format' => 'name', |
---|
37 | 'separator' => '/', |
---|
38 | 'link' => true, |
---|
39 | 'inclusive' => true, |
---|
40 | 'reverse' => true, |
---|
41 | ); |
---|
42 | |
---|
43 | $args = wp_parse_args( $args, $defaults ); |
---|
44 | |
---|
45 | foreach ( array( 'link', 'inclusive', 'reverse' ) as $bool ) { |
---|
46 | $args[ $bool ] = wp_validate_boolean( $args[ $bool ] ); |
---|
47 | } |
---|
48 | |
---|
49 | $parents = get_ancestors( $term_id, $taxonomy, 'taxonomy' ); |
---|
50 | |
---|
51 | if ( $args['inclusive'] ) { |
---|
52 | array_unshift( $parents, $term_id ); |
---|
53 | } |
---|
54 | |
---|
55 | /** |
---|
56 | * @since 5.7.3 |
---|
57 | */ |
---|
58 | if( $args['reverse'] ){ |
---|
59 | $parents = array_reverse( $parents ); |
---|
60 | } |
---|
61 | |
---|
62 | foreach ( $parents as $term_id ) { |
---|
63 | $parent = get_term( $term_id, $taxonomy ); |
---|
64 | $name = ( 'slug' === $args['format'] ) ? $parent->slug : $parent->name; |
---|
65 | |
---|
66 | if ( $args['link'] ) { |
---|
67 | $list .= '<a href="' . esc_url( get_term_link( $parent->term_id, $taxonomy ) ) . '">' . $name . '</a>' . $args['separator']; |
---|
68 | } else { |
---|
69 | $list .= $name . $args['separator']; |
---|
70 | } |
---|
71 | } |
---|
72 | |
---|
73 | return $list; |
---|
74 | } |
---|