Occasionally, when working on a project there are times in which it’d be nice to have an API function to help achieve whatever it is that needs to be done. Case in point: the ability to retrieve a taxonomy by term ID.
Granted, it’s not a hard thing to do, but having the ability to retrieve the information from pre-existing functionality is always nice.
But when that’s not possible, we write our own way to do it, right?
Retrieve a Taxonomy By Term ID
When I set out to do something like this, I generally run the idea by a couple of other developers to make sure I’m not missing some function that does exist in WordPress core and I just don’t know about it.
(This happens more than you may think, but that may be more of a problem on my end than anything else. Even still, WordPress is a big piece of software :).
The use case for something like this is simple:
- I’ve a term ID that’s been saved to the database through some other means (such as a select element elsewhere in the application such as the dashboard).
- I want to display the taxonomy name associated with that term ID.
Conceptually, I think of this as a type of reverse look. Normally, we can take a taxonomy and look up its terms. But to by a taxonomy by term ID is going in the other direction.
The code should be easy to follow (if not for the comments above the function), but it will return either an empty string or the taxonomy name based on the term ID.
Since get_term retrieves a WP_Term object, we can look at the term’s taxonomy property to grab the name. I then trim the string just in case (if I’m working with someone else’s code, I never know if it’s padded or not and I don’t want extraneous characters).
Regardless, now you have a function available to grab the taxonomy name by the term ID. If an empty string is returned, then no taxonomy name was found.