Save taxonomy terms programmatically
<?php
...
//Tags
$node->taxonomy = array('tags' => array( $vid => 'tag1, tag2'));
//Single term
$node->taxonomy = array( $vid => $tid);
taxonomy_node_save($node, $node->taxonomy);
//OR
node_save($node);
?>Set a term to a node by a known vocabulary and term name
<?php
/**
* Get taxonomy array to add to node object on presave in hook_nodeapi
*
* @param unknown_type $value
* @param unknown_type $voc
* @return unknown
*/
function linkchecker_get_term($value="New", $voc = "features_link_state"){
$vid = db_result(db_query("SELECT vid FROM {vocabulary} WHERE module = '%s';", $voc));
$term = db_fetch_array(db_query('SELECT tid FROM {term_data} WHERE name LIKE "%s" AND vid = %d', $value, $vid));
return array($indication['vid'] => array($term['tid'] => $term['tid']));
}
...
$node->taxonomy = linkchecker_get_term();
?>Update Taxonomy term tags, remove existing from the vocabulary and set a new one. If it does not exist add it first and then set it to the node.
<?php
/**
* Set a clean new taxonomy tag
*
* @param unknown_type $nid
* @param unknown_type $voc
* @param unknown_type $tag
* @return unknown
*/
function _set_clean_term($nid, $voc, $tag){
if (is_numeric($nid) AND is_numeric($voc) AND is_string($tag)) {
if($result = db_query("SELECT tid FROM {term_data} WHERE vid = %d", $voc)) {
while ($data = db_fetch_object($result)) {
$terms[$data->tid] = $data->tid;
}
}
$terms_tids = implode(", ", $terms);
db_query('DELETE FROM {term_node} WHERE nid = %d AND tid IN (%s)', $nid, $terms_tids);
$tid = db_result(db_query("SELECT tid FROM {term_data} WHERE name = '%s' AND vid = %d", $tag, $voc));
if (!$tid) {
//Add new term
$edit = array(
'vid' => $voc,
'name' => $tag,
);
taxonomy_save_term($edit);
$tid = $edit['tid'];
}
db_query("INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)", $nid, $nid, $tid);
return $tid;
}
}
?>Knowledge keywords:
