Get the term for an taxonomy archive when the term has no posts

Seems like it should be simple (the Stack Overflow catchphrase)

A taxonomy archive taxonomy-my-taxonomy.php, I’m using $terms = get_the_terms($post->ID, 'my-taxonomy'); to get the properties of the archive term.

Trouble is this is the post term(s) not the archive term.

It assumes that $post->ID exists, ie this taxonomy has posts. I would like to display the page with the various term properties even if it’s empty.

How?

1 Answer
1

You could simply check if a post exists. Otherwise, you can get the currently viewed term:

// Check if we have posts to work with
if( ! have_posts() ) {
    $term = get_queried_object(); // Get the current term
}

// Check if we have a term to work with
if( ! empty( $term ) ) {
    echo $term->name; // Output term properties
}

Since you’re using this in a taxonomy template, get_queried_object() should return a WP_Term object.

Leave a Comment