I'm connecting terms to a node in some different situations and I'm a bit confused by how $node->taxonomy behaves differently in different situations.
I have an xml import sort of like this:
// Checks if the node exists
if ($nid) {
$node = node_load($nid, NULL, TRUE);
}
else {
$node = new stdClass();
$node->type = 'type';
$node->uid = 1;
$node->title = '';
$node->model = $model;
$node->sell_price = 0;
# etc..
}
// Adds the term
$tid = trim($product->getElementsByTagName('tid')->item(0)->nodeValue;
$node->taxonomy[$tid] = $tid;
// Saves the node
node_save($node);
Obviously the above is simplified, but that's the important bits. It works perfectly. Note how I'm adding the terms here.
And i also have something like this:
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
switch ($op) {
case 'presave':
// Empties taxonomy[$vid] to avoid duplicate terms
$node->taxonomy[$vid] = array();
// Connects the node to a term depending on the value in field_fmt
switch ($node->field_fmt[0]['value']) {
case 1:
$node->taxonomy[$vid][$tid1] = $tid1;
break;
case 2:
$node->taxonomy[$vid][$tid2] = $tid2;
break;
default:
$node->taxonomy[$vid][$tid3] = $tid3;
}
break;
}
}
Here I have to add the terms differently.
How and when did the structure of $node->taxonomy change when 'presave' is called on the very first line of the node_save() function?
function node_save(&$node) {
// Let modules modify the node before it is saved to the database.
node_invoke_nodeapi($node, 'presave');
I don't understand why I suddenly need to specify the vocabulary ID in 'presave' when I didn't before node_save. Also, I understand that the syntax is different in 'presave' depending on whether the vocabulary is tags, single select or multi select. Why isn't it just $node->taxonomy[$tid] = $tid always?
Also, are there better ways of connecting terms to nodes?
Thanks in advance and apologies if this has been asked before. I've googled the topic a lot, but everyone seems to have different opinions on how to connect terms to nodes programmatically.