In drupal 7, Taxonomy terms are attached as regular fields. So $node->taxonomy
is no longer a standard property that Taxonomy module picks up.
If your field name is field_beaches_tags
, assign tags to the node as below.
$node->field_beaches_tags[$node->language][]['tid'] = 23;
Note that the 23
above is the term ID of the taxonomy term.
If you have an array of terms, you can assign all of them like below:
$terms = array(23, 45, 678, 1212);
foreach ($terms as $tid) {
$node->field_beaches_tags[$node->language][]['tid'] = $tid;
}
Keys in the $node->field_beaches_tags[$node->language]
array will be used as delta values of the field.
Create a new taxonomy term
$term = new stdClass();
$term->name = ‘My New Term Name’;
$term->vid = 'vocabulary_id';
taxonomy_term_save($term);
Now, $term->tid
will be populated with the new term ID that you can use.
See taxonomy_term_save() for the API doc.
taxonomy_get_term_by_name() can be used to load terms by a given name.
$term = taxonomy_get_term_by_name('my existing term name', 'beach_terms');
// $term->tid will now be in place.
Your overall code can be like the following.
$terms_given = array('Miami', 'Colombo', 'Pizza');
$node = new stdClass();
$node->language = LANGUAGE_NONE;
$node->promote = 0;
$node->uid = 1;
$node->type = 'content_type';
foreach ($terms_given as $term_name) {
$terms_matched = taxonomy_get_term_by_name($term_name, 'beach_terms'); // "beach_terms" is the machine name of vid 1.
if ($terms_matched) {
//We blindly use the first match. Not very elegant.
$first_term = current($terms_matched);
$node->field_beaches_tags[$node->language][] = (array) $first_term;
}
else {
$term = new stdClass();
$term->name = term_name;
$term->vid = 1; // Vid from the question.
taxonomy_term_save($term);
$node->field_beaches_tags[$node->language][] = (array) $term;
}
}