Ruin The assorted ramblings of Brendan Tobolaski

Two Drupal 7 Taxonomy Tips

This is precisely what I was looking for when I wrote my rant about including the version number. I was trying to figure out how you specify the category and tags when pragmatically creating nodes in Drupal 7 using node_save(). So here they are assuming that you already have your $node setup with the other values that you need.

Adding a category to the node

This should be all you need:

$node->field_category[$node->language][]['tid'] = $category_tid;

Unless you have a parent in which case you will need to add the parents all the way up to the top level. Here is an example if you already have the 1 parent’s tid:

$node->field_category[$node->language][]['tid'] = $parent_tid;
$node->field_category[$node->language][]['tid'] = $category_tid;

Adding a tag to the node

This one is pretty simple as you don’t need to worry about any sort of hierarchy.

$node->field_tags[$node->language][]['tid'] = $tag_tid;