I'm trying to list just the first taxonomy term outside the loop.

This is working fine but it lists all terms, and I just need the first - any suggestions?

    $taxonomy = 'taxonomy-name-here';
    $queried_term = get_query_var($taxonomy);

    $terms = get_terms($taxonomy, 'slug='.$queried_term);
    if ($terms) {
      foreach($terms as $term) {
    echo ' ' . $term->name . ' ';

Edit: clarification: the above seems to be returning all categories within the taxonomy, I'm only looking to get the taxonomy category of the current page.

Update: I found a simple answer!:

$categories= wp_get_object_terms($post->ID, 'taxonomy-name');
echo $categories[0]->name;
  • ah, it all becomes clear now. you're on a single post page trying to get terms associated with that post, not a taxonomy term page, which is why get_query_var($taxonomy); is empty. – Milo Aug 25 '11 at 17:58
$taxonomy = 'taxonomy-name-here';
$queried_term = get_query_var($taxonomy);
$term = get_term_by( 'slug', $queried_term, $taxonomy );
echo $term->name;
| improve this answer | |
  • Thanks for the reply, but that doesn't seem to return anything for me. – maikunari Aug 24 '11 at 21:19
  • is this not a taxonomy term page? – Milo Aug 24 '11 at 21:24
  • No, this is going in the title tag, called only on the taxonomy page though. – maikunari Aug 24 '11 at 21:31
  • I'm confused. yes it is a taxonomy page, or it isn't? taxonomy page meaning site.com/your-taxonomy-name/the-taxonomy-term/, that's the only context in which get_query_var($taxonomy); is going to contain a taxonomy term. – Milo Aug 24 '11 at 22:29
  • Sorry about that, yes it is a taxonomy page then. The code I posted above using get_terms() was working so that means your code should work too right? – maikunari Aug 24 '11 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.