Programmatically Add Taxonomy Terms in Drupal 7

It took a while for me to figure this out, so I thought I would create a quick post to help anyone in the same situation.

What I needed to do was add taxonomy terms to selected nodes using Views Bulk Operations. It seemed like it would be easy coming from Drupal 6, but I found the list of possible operations lacking. I did not do research to find out how to add an operation, I decided to just "Execute arbitrary PHP script," the only operation that would let me deal with taxonomies.

After choosing this option, the php textarea gives help text that says, "You can use variables $entity and $context in your snippet." Great entities! Entities seem to be doing amazing things in Drupal 7, but I still haven't gotten my head around the concept yet. What I do know is that I could call the $entity variable from this screen "admin/content2," but I could not get the $node. The $entity was, in fact, the same as the $node object, except I couldn't save it. So once I did figure out how to add taxonomy terms programmatically, I could not use entity_save($entity_type, $entity) to save the node object. Annoying! Apparently, entity_save does not yet and may never (in D7) save the node object.

The quick and dirty solution is this:

$node = node_load($entity->nid);
$node->field_article_type['und'][0] = array('tid' => 46);

Paste that (without the php tags) into the execute php code textarea, change 'field_article_type' to whatever your actual taxonomy field name is and change the 'tid' to the correct tid and you should be good to go.

Site Region: