Create a taxonomy term programmatically

Public

A little (beta) toolkit function to create a taxonomy term with a given name in a given vocabulary.

N.B. : I'm not sure if usage of another language than 'en' could work for example with modules like Entity Translations. Feel free to give me your feedback about that behavior. The function may be more strong if it could test if the language code exists.

Get raw version
php
  1. /**
  2.  * Helper function to create a taxonomy ter
  3.  * @param string $vocabulary_name machine name of the vocabulary
  4.  * @param string $term_name title of the term
  5.  * @return mixed return tid if creation succeed, else return
  6.  * FALSE
  7.  */
  8. function _my_module_create_taxonomy_term($vocabulary_name, $term_name = 'my new term', $lang = 'en') {
  9. $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  10. if ($vocabulary !== FALSE && is_string($term_name)) {
  11. $term = new stdClass();
  12. $term->name = $term_name;
  13. $term->vid = $vocabulary->vid;
  14. $term->language = $lang;
  15. taxonomy_term_save($term);
  16. return $term->tid;
  17. }
  18. return FALSE;
  19. }