Get the currently selected custom taxonomy term

When you land on a taxonomy template you might want to find out what the currently selected term is. E.g. you might want to either display the term name or make the term visually look different.

To obtain the currently selected term object use the following code:

$term = get_term_by('slug', get_query_var('taxonomy_name'), 'taxonomy_name' );

Notice how the term is requested by using the slug, not the Id. This is because the Query Var structure holds the selected term name for custom taxonomies, not the Id. When doing this for the built in taxonomies (default post categories & tags) you need to use the Id instead of the slug. The taxonomy_name is the name you used when you created your custom taxonomy.

The term object returned by get_term_by has the following structure:

stdClass Object
(
   [term_id] => 4
   [name] => Taxonomy
   [slug] => taxonomy
   [term_group] => 0
   [term_taxonomy_id] => 4
   [taxonomy] => "taxonomy_name"
   [description] => "Your taxonomy description.";
   [parent] => 0
   [count] => 2
)

To get a link to the term use the get_term_link WordPress function:

$href = get_term_link($term, 'taxonomy_name');

Bon App├ętit!

Tagged with: