Yawd website


How to automatically add taxonomy term relations when adding content in Drupal 7

Let's suppose we want our Drupal article content type to have a parent category and a sub-category. We have defined a 'categories' vocabulary and we are also able to add new terms and set their parent elements. When using the administration UI to add a new article we can create a new category, set a new sub-category and both taxonomy terms will be saved along with the article. However, the sub-category won't be connected with its parent category automatically. We need to manually visit the taxonomy terms list and set the sub-category's parent category term.

This is a problem I came across when working on a yawd project and to solve it I had to create a simple module that programmatically correlates the sub-category with its parent category field. The module implements the hook_node_presave method to inject our code just before the node (article) gets saved. Assuming field_tag_lvl_1 is the category taxonomy reference field and field_tag_lvl_2 the sub-category equivalent the code should be as follows:

 * Set taxonomy relations just before the node gets saved
 * @param $node the node about to get saved
function d7xtax_node_presave($node) {
	if($node->type=='content') {
		$tax1 = $node->field_tag_lvl_1['und'][0];
		$tax2 = $node->field_tag_lvl_2['und'][0];

		//save parent taxonomy term

		//create child taxonomy's parent list
		if( $temp_tax = taxonomy_term_load($tax2['tid'])) {
			$parents = array();
			$exists = false;
			foreach(taxonomy_get_parents($tax2['tid']) as $value) {
				if($tax1['tid'] == $value->tid) {
					$exists = true;
				array_push($parents, $value->tid);
			if (!$exists) {
				array_push($parents, $tax1['tid']);
			$tax2['parent'] = $parents;
		} else {
			$tax2['parent'] = array($tax1['tid']);

		//save child taxonomy

Please note that the above code uses Drupal 7's API and is not valid for Drupal 6 installations.

Comments powered by Disqus