19

The only function on the list of taxonomy.module functions that looks like it does what I want appears to be a private function (_taxonomy_get_tid_from_term).

What function am I supposed to use if all I know is the taxonomy term name and I need to find out its ID?

14

It's taxonomy_get_term_by_name() which you use as in the following code.

$term_array = taxonomy_get_term_by_name('Foo');
$term = reset($term_array); # get the first element of the array which is our term object
print $term->name;
  • 1
    That seems to give me an array rather than a TID. $foo[0]->tid doesn't do anything because it returns an array keyed with TIDs. So to get the TID I need the TID, or to do a foreach() even though it's only on one item? Otherwise: Undefined offset: 0 – beth Jul 10 '12 at 14:32
  • 3
    It returns an array as there is nothing preventing multiple terms from having the same name. You can't know it's only one item. – Letharion Jul 10 '12 at 14:35
  • 2
    @beth, either use the second parameter to limit to a particular vocabulary, or loop through with foreach ($terms as $term) and check the $term->vid to make sure you have the right one. – mpdonadio Jul 10 '12 at 14:37
  • I just quickly typed in the D6 version that I am used to. I see now from your links/urls included that you are running D7. The comments above should clarify things for you. – Jimajamma Jul 10 '12 at 14:42
22

taxonomy_get_term_by_name() will do the trick:

$terms = taxonomy_get_term_by_name($row->field_term_name);
if (!empty($terms)) {
  $first_term = array_shift($terms);
  print $first_term->tid;
}
  • 4
    There is also a second argument that got added to Drupal 7 to limit this to a particular vocabulary. This eliminates the need to loop through the results to find the term you want when you may have multiple tids that share the same name. – mpdonadio Jul 2 '13 at 18:44
  • 2
    Missing semicolon in the line $first_term = array_shift($terms); – Kevin Siji Feb 17 '15 at 4:41
1

This function worked for me:

/**
 * Return the term id for a given term name.
 */
function _get_tid_from_term_name($term_name) {
  $vocabulary = 'tags';
  $arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
  if (!empty($arr_terms)) {
    $arr_terms = array_values($arr_terms);
    $tid = $arr_terms[0]->tid;
  }
  else {
    $vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
    $term = new stdClass();
    $term->name = $term_name;
    $term->vid = $vobj->vid;
    taxonomy_term_save($term);
    $tid = $term->tid;
  }
  return $tid;
}

If you are using another vocabulary (different from Tags), then modify in the code above the line:

$vocabulary = 'tags';

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.