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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x