My goal is to create some nodes programmatically and tag them with taxonomy terms on creation. The taxonomy term may need to be created, or if it already exists, just added. I'm currently just using an incrementer as the tag, so if I'm making 5 nodes I want them tagged 0-4. Here is the code:
//see if this term already exists and fetch it if it does
$term = taxonomy_get_term_by_name($i);
//if it doesn't exist, make it
if ($term == array()){
//make a new class to hold the term for taxonomy 1
$taxonomy = new stdClass();
$taxonomy->name = $i;
$taxonomy->vid = 1;
taxonomy_term_save($taxonomy);
//now fetch it so we have it's tid
$term = taxonomy_get_term_by_name($i);
}
//set $tid as it's returned from taxonomy_get_term_by_name
$tid = key($term);
//tag the node with the appropriate tag
$node->field_tags['und'][0] = array('tid' => $tid);
//save the tagged node
node_save($node);
$i++;
When I run this it makes the nodes and terms if needed.
taxonomy_term_data table has the 5 terms in it, named 0-4.
taxonomy_index table has nids 0-4 properly associated with tids 0-4.
Also field_data_field_tags table has the right field_tags_tids 0-4 associated with the right entity_id 0-4.
So far so good. However when I view the nodes, they are all tagged 4. Furthermore if I click on 4, it doesn't bring up any of the other nodes, so it seems to be unique, but they all say they are tagged 4 rather than being individually tagged 0-4. Any ideas?
Comments
This $i++; makes me wonder
This
$i++;makes me wonder what $i holds, that code suggests an integer while$taxonomy->name = $i;suggests a string. When you say they are all tagged "4" is that visually what shows? What is the tid in the link (it sounds like it is different in each case) suggesting there is a bug in the logic in the code not shown.This helped, thanks
This was a big help. You were correct that something in the rest of the code was messing it up. I'd copy/pasted some code for programmatically making nodes and it included this code:
Looks like this was giving the nodes the same path. :P Commenting this out did the trick. Thanks for getting me over that hump.
FYI: I was looking for how to
FYI:
I was looking for how to create nodes and their taxonomies programatically, and found this:
http://drupal.org/node/889058