I have a script which successfully creates new nodes. But I'm having trouble setting the taxonomy before saving.
I believe in Drupal 6 I would use this method.
$cat1_tid = taxonomy_get_term_by_name($data[$i]['cat1']);
$cat2_tid = taxonomy_get_term_by_name($data[$i]['cat2']);
$cat3_tid = taxonomy_get_term_by_name($data[$i]['cat3']);
$node->taxonomy = array($cat1_tid, $cat2_tid, $cat3_tid);
I think in Drupal 7 I would do this (my field name is Catalog)
$node->taxonomy_catalog['und'][0] = array($term1Obj, $term2Obj);
taxonomy_get_term_by_name doesn't seem to return the correct object to insert into the node object.
If anyone can shed some light, appreciated.
Thanks
EDIT
Solution:
// Taxonomy
$categories = array($data[$i]['cat1'], $data[$i]['cat2'], $data[$i]['cat3']);
foreach ($categories as $key => $category) {
if ($term = taxonomy_get_term_by_name($category)) {
$terms_array = array_keys($term);
$node->taxonomy_catalog[LANGUAGE_NONE][$key]['tid'] = $terms_array['0'];
}
}
Perhaps my experience is unique, but I found that using
caused an error.
I found that after $term is saved, there is no need to fetch the newly created term.
The $term object is updated to include the new tid.
Below is some quick-and-dirty code I used recently to import "command" nodes into a site. Mid-way down, the foreach loop takes care of creating and assigning terms, as needed.
Here you are, this code successfully add a new term to the node before the node is created.
Any answer that use LANGUAGE_NONE or 'und' to alter a field is not the proper way of doing it as it assumes that the drupal site is one language. The proper way to edit a field is to use entity_metadata_wrapper.