I have a $category variable containing country names separated by comma. So I use the following code to save them as taxonomy terms:
$tids = array(); $ctids = array();
$category = explode(',',$category);
foreach($category as $cat) {
insert_term_if_not_exists($cat, 'countries');
$term_country = taxonomy_get_term_by_name($cat);
$tid_country = key($term_country);
$lang_country = field_language('node', $node, 'field_country');
array_push($ctids, $tid_country);
}
foreach ($ctids as $index => $ctid) {
$node->field_country[$lang_country][$index]['tid'] = $ctid;
}
As you see the above code uses the insert_term_if_not_exists()
function which works perfectly well to check if a taxonomy term exists and to create it programmatically if it doesn't:
function insert_term_if_not_exists($term_name, $vocabulary_name) {
$vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
$matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
if(empty($matched_terms)) {
$term = new stdClass();
$term->vid = $vocabulary->vid;
$term->name = $term_name;
taxonomy_term_save($term);
} else {
$term = array_shift($matched_terms);
}
return $term;
}
However, I also need to check and avoid creating a new taxonomy term if it is a synonym of already existing another taxonomy term. So I modified the above code in the following way:
function insert_term_if_not_exists($term_name, $vocabulary_name) {
$vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
$matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
if(empty($matched_terms)) {
$matched_synonym = synonyms_get_term_by_synonym($term_name, $vocabulary);
if (empty($matched_synonym)) {
$term = new stdClass();
$term->vid = $vocabulary->vid;
$term->name = $term_name;
taxonomy_term_save($term);
} else {
/*
* Here I need to do something, but don't know what exactly. Using
* $term = taxonomy_term_load($matched_synonym);
* here doesn't work.
*/
}
} else {
$term = array_shift($matched_terms);
}
return $term;
}
Having troubles to make it work properly.
synonyms_get_term_by_synonym()
expects its$vocabulary
parameter to be a fully loaded vocabulary object, so make sure you're passing a valid vocabulary object. If it isn't, that could be the cause of the the error you get on line 356.