At the beginning, get taxonomies registered for a given type of post with get_object_taxonomies()
. Then check which ones are hierarchical, e.g. using is_taxonomy_hierarchical()
conditional tag. The last step is to display the lists.
// current post ID
$post_id = get_the_ID();
// taxonomies registered for this type of posts
$taxonomies = get_object_taxonomies( get_post_type() );
$taxs_tree = []; // hierarchical taxonomies
$taxs_flat = []; // non-hierarchical taxonomies
foreach ( $taxonomies as $tax )
{
if ( is_taxonomy_hierarchical( $tax ) )
$taxs_tree[] = $tax;
else
$taxs_flat[] = $tax;
}
Get terms from each taxonomy and display them.
// get terms as links
$terms_flat = $terms_tree = [];
foreach ( $taxs_tree as $tax ) {
$terms_tree[] = get_the_term_list( $post_id, $tax );
}
foreach ( $taxs_flat as $tax ) {
$terms_flat[] = get_the_term_list( $post_id, $tax );
}
echo '<span id="one">';
foreach ( $terms_tree as $links ) {
echo $links;
}
echo '</span>';
Or:
//
// terms assigned to post, ordered by name, from all hierarchical taxonomies
$args = [
'taxonomy' => $taxs_tree, // here you can pass array of taxonomies
'object_ids' => get_the_ID(), // get only terms assigned to this post (current post)
//'orderby. => 'name', // default
];
$terms_tree = get_terms( $args ); // array of WP_term objects
//
// terms assigned to post, ordered by name, from all non-hierarchical taxonomies
$args['taxonomy'] = $taxs_flat;
$terms_flat = get_terms( $args ); // array of WP_term objects
//
// display
echo '<span id="one">';
foreach ( $terms_tree as $term ) {
$link = get_term_link( $term );
if ( is_wp_error( $link ) ) {
continue;
}
echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a> ';
}
echo '</span>';
// the same with $terms_flat
The second solution (with get_terms
) sort terms from all hierarchical taxonomies by name, while the first one (with get_the_term_list
) sort terms from each hierarchical taxonomy separately.
References:
- get_terms() – function, parameters
- get_term_link()
- get_the_term_list()