get_term_parents_list()
最后更新于:2021-11-27 00:57:39
get_term_parents_list( int$term_id, string$taxonomy, string|array$args=array())Retrieves term parents with separator.
参数
- $term_id
-
(int) (Required) Term ID.
- $taxonomy
-
(string) (Required) Taxonomy name.
- $args
-
(string|array) (Optional) Array of optional arguments.
-
‘format’
(string) Use term names or slugs for display. Accepts ‘name’ or ‘slug’. Default ‘name’. -
‘separator’
(string) Separator for between the terms. Default ‘/’. -
‘link’
(bool) Whether to format as a link. Default true. -
‘inclusive’
(bool) Include the term to get the parents for. Default true.
Default value: array()
-
‘format’
响应
(string|GC_Error) A list of term parents on success, GC_Error or empty string on failure.
源文件
文件: gc-includes/category-template.php
function get_term_parents_list( $term_id, $taxonomy, $args = array() ) {
$list = '';
$term = get_term( $term_id, $taxonomy );
if ( is_gc_error( $term ) ) {
return $term;
}
if ( ! $term ) {
return $list;
}
$term_id = $term->term_id;
$defaults = array(
'format' => 'name',
'separator' => '/',
'link' => true,
'inclusive' => true,
);
$args = gc_parse_args( $args, $defaults );
foreach ( array( 'link', 'inclusive' ) as $bool ) {
$args[ $bool ] = gc_validate_boolean( $args[ $bool ] );
}
$parents = get_ancestors( $term_id, $taxonomy, 'taxonomy' );
if ( $args['inclusive'] ) {
array_unshift( $parents, $term_id );
}
foreach ( array_reverse( $parents ) as $term_id ) {
$parent = get_term( $term_id, $taxonomy );
$name = ( 'slug' === $args['format'] ) ? $parent->slug : $parent->name;
if ( $args['link'] ) {
$list .= '<a href="' . esc_url( get_term_link( $parent->term_id, $taxonomy ) ) . '">' . $name . '</a>' . $args['separator'];
} else {
$list .= $name . $args['separator'];
}
}
return $list;
}
<?php if ( ( is_tax() || is_category() || is_tag() ) ) { $trail = ''; $home = '/<a href="' . get_home_url() . '">Home</a>'; $query_obj = get_queried_object(); $term_id = $query_obj->term_id; $taxonomy = get_taxonomy( $query_obj->taxonomy ); if ( $term_id && $taxonomy ) { // Add taxonomy label name to the trail. $trail .= '/' . $taxonomy->labels->menu_name; // Add term parents to the trail. $trail .= '/' . get_term_parents_list( $term_id, $taxonomy->name, array( 'inclusive' => false ) ); } // Print trail and add current term name at the end. echo '<p class="breadcrumb-trail">' . $home . $trail . $query_obj->name . '</p>'; } ?>