0

If I want to display all terms assigned to a custom post with custom taxonomy, I could use for eg.

<?php the_terms( $post->ID, 'custom-taxonomy', '', ", ", '' ); ?>

but in this solution I need specify name of taxonomy.

I want to display all terms from all assigned to post taxonomies, but separetly. For eg. if I have taxonomies called "holidays" and "countries" I want to display their terms like that:

<div>
    <span>[terms of "holidays"]</span>
    <span>[terms of "countries"]<span>
</div>

How can I do that automatically, without giving the names of taxonomies?

Thanks!

1 Answer 1

0

You can get the taxonomies that are registered for a post type with get_object_taxonomies(). If you pass the post object directly, you don't even need to explicitly name the post type either.

You can then loop through the result of that function to achieve the result you want:

$taxonomies = get_object_taxonomies( $post );

foreach ( $taxonomies as $taxonomy ) {
    the_terms( $post->ID, $taxonomy, '<span>', ", ", '</span>' );
}
3
  • Thank u a lot! This is what I was looking for. Tell me, is there any way to rearrange taxonomies order? Commented Jun 10, 2019 at 17:28
  • Taxonomies don’t have an order, so you’d either need to sort the taxonomies array alphabetically with asort(), or you need to write them out. Commented Jun 11, 2019 at 2:45
  • I see :) I have one more question. I'm trying to display singular name of tax, before each list of terms. I was trying use this: <?php $taxonomies = get_object_taxonomies( $post ); foreach ( $taxonomies as $taxonomy ) { $tax_name = $taxonomy->labels->singular_name; the_terms( $post->ID, $taxonomy, '<span class="e-article__category__item"><strong>' . $tax_name . ': </strong> ', ", ", '</span>' ); } ?> but notthing happen. What am I doing wrong? Commented Jun 12, 2019 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.