Check if a taxonomy term exists in a vocab

Public

Returns
1 tid exists in the vocab.
0 tid does not exist.
-1 no vocab found with the given machine name
2 vocab has no terms inside.

Can be used simply by calling as follows:
$reply = check_term_exist_in_vocab('vocab_machine_name', term_id);

</> CopyGet raw version
php
  1. /**
  2.  * function to know if a term exists in a vocab or not.
  3.  * @param
  4.  * $vocab_machine_name takes vocabulary machine name as parameter in which you want to find a term.
  5.  * $tid term id which you want to know if exists or not in the given vocab.
  6.  * @return
  7.  * 1 tid exists in the vocab.
  8.  * 0 tid does not exist.
  9.  * -1 no vocab found with the given machine name
  10.  * 2 vocab has no terms inside.
  11.  */
  12.  
  13. function check_term_exist_in_vocab($vocab_machine_name, $tid) {
  14. $vocab = taxonomy_vocabulary_machine_name_load($vocab_machine_name);
  15. if (is_object($vocab)) {
  16. $term_tree = taxonomy_get_tree($vocab->vid);
  17. if (is_array($term_tree) && !empty($term_tree)) {
  18. foreach ($term_tree as $key => $value) {
  19. $vocab_tids[] = $value->tid;
  20. }
  21. if (in_array($tid, $vocab_tids)) {
  22. return TRUE;
  23. }
  24. else {
  25. return 0;
  26. }
  27. } if (empty($term_tree)) {
  28. return 2;
  29. }
  30. } else
  31. return -1;
  32. }

Comments

hook_drupal's picture

Is there faster way to do that? maybe per EntityFieldQuery or MySQL query?!

ooops's picture

Yes hook_drupal good point.We can always enjoy entity queries since vocab is also en entity here.Here is code snippet for that.

  1. //This function needs vocab id and term id as argument ...obviously :)
  2. // Return 1 if given tid is found in vid -1 when there is no vocab with given vid or the given vocab has no term inside,0 when tid is not found inside the terms exist in vid.
  3.  
  4. function check_term_exist_in_vocab($vid, $tid) {
  5. $query = new EntityFieldQuery();
  6.  
  7. $query->entityCondition('entity_type', 'taxonomy_term');
  8. $query->propertyCondition('vid', $vid);
  9. $result = $query->execute();
  10. if (count($result) == 0) {
  11. return -1;
  12. }
  13. else {
  14. foreach ($result['taxonomy_term'] as $key => $value) {
  15. if ($tid == $key) {
  16. return 1;
  17. }
  18. }
  19. return 0;
  20. }
  21. }
  22.  
  23. Thanks hook_drupal for idea! :)