Get WordPress post taxonomy values

Taxonomies are really useful when developing a custom WordPress website. They can give you extra information you need and also allow you to narrow down your search criteria, when using custom wp_query loops.

One thing I have noticed, is how many different functions there are to retrieve the taxonomy values attributed to a particular post. The best function I have come across to date is the one below. Very simple and easy to implement. I normally wrap this snippet in another function, put it in my theme’s functions.php or plugin (depending on what the usage is), so I can call it from anywhere.

All you need to do is feed through the POST ID and the taxonomy name. This will then retrieve an object, which contains the followings fields:

  • [term_id] =>
  • [name] =>
  • [slug] =>
  • [term_group] =>
  • [term_order] =>
  • [term_taxonomy_id] =>
  • [taxonomy] =>
  • [description] =>
  • [parent] =>
  • [count] =>
  • [object_id] =>

All very useful for echoing out. You can then just specify the one you want to echo out like so, $term->slug (this will retrieve the slug. Or a very handy var_dump( $term ) will show you everything associated and you can then pick from there.

 $terms = get_the_terms( $id, $taxonomy );

 foreach( $terms as $term ) {

 echo $term->slug;