I have a custom module to that generates some sample content for my site upon installation of the module. 

I am having difficulty coming up with the correct code to create a new taxonomy term, a tag, and then add it to a node with a term reference field. 

Any help would be appreciated.


Well, I found a Backdrop CMS test that created a vocabulary and some terms and that was really helpful. 

// Create a vocabulary and a term

$vocabulary = new TaxonomyVocabulary(array(
  'name' => 'Class',
  'description' => '',
  'machine_name' => 'animal_class',

$term = entity_create('taxonomy_term', array(
  'name' => 'Mammalia',
  'description' => '',
  'format' => 1,
  'vocabulary' => 'animal_class',

I was then able to do this to add it to a node programmatically (see here for the rest of the code to add a node).

$node->field_animal_class['und'][0]['tid'] = '1';

I haven't figured out how to add a term to a node without knowing the TID.

I would think that I could add a term to the vocabulary, just by adding it to the node directory. But, I could not get that to work. Ideas?

klonos's picture

(note: untested) ...I believe that after taxonomy_term_save(), you should be able to do something like $term_id = $term->id; (or could be $term_id = $term->tid; - you need to check) to get the term ID; so then it would simply be a matter of:

$node->field_animal_class['und'][0]['tid'] = $term_id;

...or directly, w/o assigning it to a variable:

$node->field_animal_class['und'][0]['tid'] = $term->id;

Please give that a go and let us know if it worked for you.

A Google search helped me find this thread, and just wanted to confirm that the above code for creating a new term works in Backdrop 1.16.2, and you can assign the newly created term to a node field like this: 

$new_term = entity_create('taxonomy_term', array(
  'name' => <NAME>,
  'description' => '',
  'format' => 1,
  'vocabulary' => '<VOCAB_NAME>',
$node->field_category[LANGUAGE_NONE][0]['tid'] = $new_term->tid;