Retrieves term parents with separator.
Parameters
$term_id
intrequired- Term ID.
$taxonomy
stringrequired- Taxonomy name.
$args
string|arrayoptional- Array of optional arguments.
format
stringUse term names or slugs for display. Accepts'name'
or'slug'
.
Default'name'
.separator
stringSeparator for between the terms. Default'/'
.link
boolWhether to format as a link. Default true.inclusive
boolInclude the term to get the parents for. Default true.
Default:
array()
Source
function get_term_parents_list( $term_id, $taxonomy, $args = array() ) {
$list = '';
$term = get_term( $term_id, $taxonomy );
if ( is_wp_error( $term ) ) {
return $term;
}
if ( ! $term ) {
return $list;
}
$term_id = $term->term_id;
$defaults = array(
'format' => 'name',
'separator' => '/',
'link' => true,
'inclusive' => true,
);
$args = wp_parse_args( $args, $defaults );
foreach ( array( 'link', 'inclusive' ) as $bool ) {
$args[ $bool ] = wp_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;
}
Changelog
Version | Description |
---|---|
4.8.0 | Introduced. |
Example to display term parents in category archive pages. Use this in your category archive theme templates.
This is an example of what it would print on a “Grandchild Category” term page.
Parent Category/Child Category/Grandchild Category
Example of a breadcrumb trail for taxonomy pages. Use it in your theme’s taxonomy templates