Check if taxonomy term exists and save the term if it doesn't

A dynamic query can be used to check if a taxonomy term exists.

Query conditions are the taxonomy term name and the vocabulary.


/**
 * Check if taxonomy term exists and save the term if it doesn't.
 * 
 * @param string $termname
 * @param integer $vid
 */
function _process_taxonomy_terms($termname, $vid) {
	// Build in extra checks if needed.
	if(_get_taxonomy_term_id_by_name($termname, $vid) == false) {
		taxonomy_term_save(
			(object) array(
				'name' => $termname,
				'vid' => $vid,
			)
		);
	}
}

/**
 * Get taxonomy term ID by term name.
 * 
 * @param string $termname
 * @param integer $vid
 */
function _get_taxonomy_term_id_by_name($termname, $vid) {
	return db_select('taxonomy_term_data', 't')
	->fields('t', array('tid'))
	->condition('t.name', $termname)
	->condition('t.vid', $vid)
	->execute()
	->fetchField();
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.