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.

Get 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.

Luckily, it’s easy enough if you piggyback off of an existing API. Check it out:

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.

Category:
Articles
Tags:

Join the conversation! 4 Comments

  1. Handy function!

    One little issue I see, which would probably only apply in an uncontrolled environment, is that get_term() will return null if a non-existent term ID is passed, and a WP_Error object if no term ID is passed at all, and that will cause a notice when trying to access $term->taxonomy.

    • Added a short conditional to check that at the top of the function.

      Though it’s something that, like you said, is relative to an uncontrolled environment, it’s really something I should’ve had in there from the beginning.

  2. Hello,

    Is this supposed to return the name – or the slug? Maybe I have my terminology wrong, and I am actually looking for the ‘label’?? is confusing to me as it relates to Taxonomies – but lets say I have a Taxonomy ‘Fancy Cars’, with slug of ‘fancy-cars’ – with your code, I only seem to end up with ‘fancy-cars’… how to I end up with ‘Fancy Cars’?

    Hope this makes sense, thanks

Leave a Reply