Updated answer:
There’s now a core function since WordPress 4.8, to list the ancestors of a given term:
get_term_parents_list(
int $term_id,
string $taxonomy,
string|array $args = array()
)
and get_category_parents()
is a wrapper for that function with $taxonomy
as 'category'
.
Previous answer:
Here is a modified version I made from the function get_category_parents()
to support general taxonomies.
/**
* Retrieve category parents with separator for general taxonomies.
* Modified version of get_category_parents()
*
* @param int $id Category ID.
* @param string $taxonomy Optional, default is 'category'.
* @param bool $link Optional, default is false. Whether to format with link.
* @param string $separator Optional, default is "https://wordpress.stackexchange.com/". How to separate categories.
* @param bool $nicename Optional, default is false. Whether to use nice name for display.
* @param array $visited Optional. Already linked to categories to prevent duplicates.
* @return string
*/
function wpse85202_get_taxonomy_parents( $id, $taxonomy = 'category', $link = false, $separator="https://wordpress.stackexchange.com/", $nicename = false, $visited = array() ) {
$chain = '';
$parent = get_term( $id, $taxonomy );
if ( is_wp_error( $parent ) )
return $parent;
if ( $nicename )
$name = $parent->slug;
else
$name = $parent->name;
if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) {
$visited[] = $parent->parent;
$chain .= wpse85202_get_taxonomy_parents( $parent->parent, $taxonomy, $link, $separator, $nicename, $visited );
}
if ( $link )
$chain .= '<a href="' . esc_url( get_term_link( $parent,$taxonomy ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $parent->name ) ) . '">'.$name.'</a>' . $separator;
else
$chain .= $name.$separator;
return $chain;
}
You can use the function like this:
echo wpse85202_get_taxonomy_parents($cat, $tax, TRUE, ' » ');
or like
echo wpse85202_get_taxonomy_parents(65, 'country', TRUE, ' » ');