20

I'm trying to retrieve term names from taxonomies for $title. I have come across a lot Codex functions like get_post_meta(), get_the_terms() etc, which seem to only get term name from post_id, which is not what I'm looking for.

How do I get term names from term_id?

Alexandre Aimbiré
  • 1,494
  • 2
  • 14
  • 26
joe city
  • 349
  • 1
  • 3
  • 9
  • 1
    I suppose you are using Wordpress? Please add this tag to you question at least so we know what you are talking about. – Jerodev Mar 06 '17 at 08:07
  • check this link : http://wordpress.stackexchange.com/questions/16394/how-to-get-a-taxonomy-term-name-by-the-slug – HIR Mar 06 '17 at 08:13
  • 2
    https://codex.wordpress.org/Function_Reference/get_term – yivi Mar 06 '17 at 08:23
  • Possible duplicate of [Wordpress using get\_term to retrieve slug not working as expected](http://stackoverflow.com/questions/37459013/wordpress-using-get-term-to-retrieve-slug-not-working-as-expected) – yivi Mar 06 '17 at 08:32

3 Answers3

32

You may get the term name from term_id like this:

$term_name = get_term( $term_id )->name;

Explanation: get_term() returns the term object and name is one of propeties of this object.

More details on codex: https://codex.wordpress.org/Function_Reference/get_term

Rao Abid
  • 510
  • 4
  • 6
9

Please try this:

<?php $term = get_term_by( $field, $value, $taxonomy); ?>

Note:

  • $field => Just write 'id' here
  • $value => Place your 'term_id' value here
  • $taxonomy => write your custom taxonomy 'slug' here

For ex: My custom taxonomy slug is 'services' & 'term_id' is 5, so here is the code for retrieving 'term_name':

<?php $term = get_term_by( 'id', 5, 'services' ); 
echo $term->name; ?>

I hope, this may be helpful to you.

Prateek Verma
  • 869
  • 1
  • 6
  • 9
  • any reason not to call `get_term` directly? – yivi Mar 06 '17 at 10:00
  • 1
    @yivi I didn't said that get_term is not correct, you already told to use get_term in your comment that's why i gave another option other than get_term, if i also tell him to use get_term(), then what is the use of your comment. And the person who has asked the question should have a variety of answers to gain extra knowledge. It's no use to tell only one answer by all the users who provide answers. – Prateek Verma Mar 06 '17 at 10:12
  • 2
    No worries. Just wondering if there was a more interesting reason behind it. – yivi Mar 06 '17 at 10:13
  • @yivi Ok bro, no problem. – Prateek Verma Mar 06 '17 at 10:17
0
 $term = get_term_by('term_id', '1', 'category'); 
 $name = $term->name; 
Abdo-Host
  • 2,470
  • 34
  • 33