How to get the first term for the current taxonomy?

I’m using the following code to display the term for a specified taxonomy:

$terms = get_terms( "book_review" );
$category = $terms[0]->name;

However I want to display the term for whatever the currently displayed taxonomy is, rather than specifying a particular taxonomy. Basically what I’m wanting is a way to replicate the functionality of get_the_category, but for the current taxonomy instead of the current category. I’m trying to display this on a single custom post type page (single-custom_post_type_name.php)

1 Answer
1

You can use get_queried_object to get the term name.

<?php if( is_tax() ) {
    global $wp_query;
    $term = $wp_query->get_queried_object();
    $title= $term->name;
       
}  ?>

To display: <?php echo $title; ?>

If your on a taxonomy archive page you can use:

<?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>

Then to display the term: <?php echo $term->name; ?>

The following properties are available for the $term object:

  • term_id
  • name
  • slug
  • term_group
  • term_taxonomy_id
  • taxonomy
  • description
  • parent
    -count

Leave a Comment