List custom taxonomy terms
-
22-04-2021 - |
Question
I am trying to display all of the terms for a custom taxonomy(characters
), the taxonomy is related to a custom post type(books
).
What I would like to do is display all of the terms for characters
, so say for instance I have two books
, and I add three characters
to each book
, I would like all six characters to display.
I would only like to get the names, not links, or in list form, if I could get a set of objects or an array that would be preferable.
Thank you.
Solution
I believe what you are looking for is the get_terms function. I found it looking at the code for wp_tag_cloud, here is the source of the function. This little snippet should get you what you are wanting.
$terms = get_terms("characters");
if ( empty( $tags ) || is_wp_error( $tags ) )
return;
foreach ( $terms as $term ) {
echo $term->name;
}
OTHER TIPS
You can add a function to your functions.php and pass 'characters' as an argument (or the slug for your custom taxonomy) to show a comma separated list of all your terms.
function show_all_terms($taxonomy){
$taxonomy_terms = get_terms($taxonomy);
foreach($taxonomy_terms as $term){
$terms[] = $term->name;
}
if(!empty($terms)) {
echo join(", ", $terms);
}
else{
echo "No ".$taxonomy."associated with this ".get_post_type();
}
}
Now you can call this function in your templates like this:
show_all_terms('character');
// you can replace 'character' with the slug of any custom taxonomy as well.