get_the_terms()
is the function you need to get terms of a custom taxonomy associated to your post.
It is similar (but not identical) to get_the_category()
for the default category taxonomy.
[Edited to answer the first comment below]
Adapting the code you have for categories, here’s how you can display either categories or terms:
<?php
$categories = get_the_category();
$separator = ", ";
$output="";
if ($categories) {
foreach ($categories as $category) {
$output .= '<a href="' . get_category_link($category->term_id) . '">'
. $category->cat_name . '</a>' . $separator;
}
echo trim($output, $separator);
}
elseif ( $terms = get_the_terms( get_the_ID(), 'my-custom-taxonomy' ) ) {
foreach ( $terms as $term ) {
$output .= '<a href="' . get_term_link( $term, 'my-custom-taxonomy' ) . '">'
. $term->name . '</a>' . $separator;
}
echo trim( $output, $separator );
}
?>
Don’t forget to replace 'my-custom-taxonomy'
(twice) with the actual slug for your taxonomy.
Note that by using this if/else structure, if a post has both a category and a term from the custom taxonomy, then only the category will show.
One can just change the elseif
to just if
in case they want both to be displayed in such case.
References: