Answers:
使用此功能从Termname获取ID
function _get_tid_from_term_name($term_name) {
$vocabulary = 'tags';
$arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
if (!empty($arr_terms)) {
$arr_terms = array_values($arr_terms);
$tid = $arr_terms[0]->tid;
}
else {
$vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
$term = new stdClass();
$term->name = $term_name;
$term->vid = $vobj->vid;
taxonomy_term_save($term);
$tid = $term->tid;
}
return $tid;
}
以编程方式创建节点时,可以将其分配给以下任何术语:
$node = new stdClass();
$node->type = 'YOUR_CONTENT_TYPE_NAME';
$node->title = 'title';
$node->language = LANGUAGE_NONE;
node_object_prepare($node);
//id of your taxonomy term
$tid = 1;
//add term to a node field
//field_yourfield_name - machine name of your term reference field
$node->field_yourfield_name[$node->language][0]['tid'] = $tid;
node_save($node);
您可以使用一些实体元数据包装器来实现,例如:
try {
$w_node = entity_metadata_wrapper('node', $entity);
$w_some_term = entity_metadata_wrapper('taxonomy_term', 1234);
$w_node->field_term_ref = $w_some_term->tid->value();
$w_node->save();
} catch (Exception $e) {
drupal_set_message(t('Error for node: @title, message: @error.',
array('@title' => $w_node->title->value(), '@error' => $e->getMessage())), 'error');
watchdog_exception('foo', $e);
}