Advertising sustains the DA. Ads are hidden for members. Join today

Computed Field

Adding a field to a vocabulary

Last updated on
30 April 2025

This snippet takes a variable $my_field and inserts it as a term in a vocabulary. It also checks for existing terms with the same name and will reuse those terms. You can do this with a free tagging vocabulary to group nodes by your calculated field values or just about anything.

Before using this snippet you need to figure out the vid (vocabulary ID) of the vocabulary that will get the new term. If you go to the edit page for the vocabulary you want the vid is the number at the end of the url (mysite.com/admin/content/taxonomy/edit/vocabulary/#). Take that number and assign it to $vid in the code below. You will also need to assign $my_field to whatever you want the term to be (treat it like your $node_field[0]['value'] assignment).

	$vid = Put your vocabulary ID here

	$escaped = check_plain($my_field);
	$existing_terms = module_invoke('taxonomy', 'get_term_by_name', $escaped);
	if (count($existing_terms) > 0) {
		foreach ($existing_terms as $existing_term) {
			if ($existing_term->vid == $vid) {
				$term_id = $existing_term->tid;
			}
		}
	} else { //the term exists
		$edit = array('name' => $escaped, 'vid' => $vid);
		taxonomy_save_term($edit);
		$term_id = $edit['tid'];
	}

	// associate node and term
	$node->taxonomy = array($vid => array($term_id => $term_id));

Help improve this page

Page status: Not set

You can: