/**
* Modifies a node object adding taxonomy terms and, optionally, modifying a
* content_taxonomy type field.
*
* @param <type> $node
* A node object.
* @param <type> $vid
* The vocabulary ID for the tags.
* @param <type> $tags
* An array of strings to use for the term names.
* @param <type> $not_found_action
* Action to take when terms are not found. Options are: 'ignore' (default)
* which will simply not insert that term into the node, 'create' will create
* new taxonomy terms, and 'other' will assign the term 'other' for a term that
* was not found.
* @param <type> $fieldname
* Optional; a content_taxonomy field machine name. E.g. field_my_tags
* @return
* A node object that can be stored in the database using node_save().
*/
function my_nodeobject_add_content_taxonomy(&$node, $vid, $tags = array(), $not_found_action = 'ignore', $fieldname = NULL) {
static $translate, $errors;
if (empty($translate)) {
// The following contains an array of translation rules. For instance,
// If you'd like to convert an incoming terms 'en' and 'eng' into 'english'
// for the vocabulary ID 6, write:
// $translate[6] = array('en' => 'english', 'eng' => 'english');
$translate = array(
29 => array(
'en' => 'english',
'sp' => 'spanish',
),
);
}
// Convert a single tag in a string to a one-element array.
if (!is_array($tags)) {
$tags = array($tags);
}
// Cycle through each given tag
foreach ($tags as $term_name) {
$term_name = trim($term_name);
if ($term_name == "") continue;
// Translate if necessary.
if (isset($translate[$vid][$term_name])) {
$term_name = $translate[$vid][$term_name];
}
// Get all terms with this name
$terms = taxonomy_get_term_by_name($term_name);
if (sizeof($terms) == 0) {
if ($not_found_action == "use_other") {
$terms = taxonomy_get_term_by_name("Other");
}
elseif ($not_found_action == "create") {
// Create a new tag with this term
$term_to_import= array(
'name' => $term_name,
'vid' => $vid,
);
$ok = taxonomy_save_term($term_to_import);
$term_tmp = taxonomy_get_term($term_to_import['tid']);
$terms = array($term_tmp);
}
else {
if (empty($errors[$vid][$term_name])) {
drupal_set_message("WARNING: Could not find '{$term_name}' in <a href=/admin/content/taxonomy/{$vid}>vid={$vid}</a>");
// Mark so error is not flagged again
$errors[$vid][$term_name] = 1;
}
continue;
}
}
foreach ($terms as $term) {
if ($term->vid == $vid && $term->parent == 0) {
if ($fieldname) {
$node->{$fieldname}[]['value'] = (string)$term->tid;
}
$node->taxonomy[$term->tid] = $term;
}
}
}
if (isset($node->$fieldname) && !is_array($node->$fieldname)) {
$node->$fieldname[0]['value'] = '';
}
}