0

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;
1
  • 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
    Commented Aug 25, 2011 at 17:58

1 Answer 1

1
$taxonomy = 'taxonomy-name-here';
$queried_term = get_query_var($taxonomy);
$term = get_term_by( 'slug', $queried_term, $taxonomy );
echo $term->name;
9
  • Thanks for the reply, but that doesn't seem to return anything for me.
    – maikunari
    Commented Aug 24, 2011 at 21:19
  • is this not a taxonomy term page?
    – Milo
    Commented Aug 24, 2011 at 21:24
  • No, this is going in the title tag, called only on the taxonomy page though.
    – maikunari
    Commented Aug 24, 2011 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
    Commented Aug 24, 2011 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
    Commented Aug 24, 2011 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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