Add “Delete All Terms” button to Drupal 7 Vocabulary Page

Posted on: October 10th, 2013 by admin No Comments

Sometimes it is necessary to delete all terms from a taxonomy however Druapl does not provide any functionality to do this.

I’m using the jQuery Easy Confirm Dialog plugin for this. First download the library from here and put this in your themes js folder.

We can then add a “Delete All Terms” button with a little code in a custom module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function hook_form_alter(&$form, &$form_state, $form_id) {
	switch($form_id) {
		case 'taxonomy_overview_terms':
 
			if($form['#total_entries']) {
				drupal_add_library('system', 'ui.dialog');
				drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME').'/js/jquery.easy-confirm-dialog.js');			
				$js = 'jQuery(document).ready(function($){$(".confirm").easyconfirm({locale: { title: \'Delete all '.$form['#vocabulary']->name.' terms\', button: [\'No\',\'Yes\']}});});';
				drupal_add_js($js, array('type'=>'inline'));
				$form['actions']['delete_all'] = array(
					'#markup' =&gt; '<a class="button confirm" title="Are you sure you want to delete all terms from the '.$form['#vocabulary']-&gt;name.' vocabulary?" href="/admin/structure/taxonomy/'.$form['#vocabulary']-&gt;vid.'/delete-all">Delete All Terms</a>',
					'#weight' =&gt; 10,
					'#attributes' =&gt; array('class' =&gt; array('button'))
				);
			}
 
			break;
	}
}

Now we need to define the path to our function to delete the terms:

1
2
3
4
5
6
7
8
9
10
11
function hook_menu() {
	$items = array();
	$items['admin/structure/taxonomy/%/delete-all'] = array(
		'title' =&gt; 'Delete all taxonomy terms',
		'type' =&gt; MENU_CALLBACK,
		'page callback' =&gt; 'delete_all_taxonomy_terms',
		'page arguments'	=&gt;	array(3),
		'access arguments' 	=&gt; 	array('administer taxonomy'),
	);
	return $items;
}

And finally add the functionality to actually delete the terms:

1
2
3
4
5
6
7
8
9
10
11
12
13
function delete_all_taxonomy_terms($vid) {
	$vocabulary = taxonomy_vocabulary_load($vid);
	$query = new EntityFieldQuery();
	$result = $query
		-&gt;entityCondition('entity_type', 'taxonomy_term')
		-&gt;propertyCondition('vid', $vid)
		-&gt;execute();
	foreach($result['taxonomy_term'] as $term) {
		taxonomy_term_delete($term-&gt;tid);
	}
	drupal_set_message('All terms have been deleted from the '.$vocabulary-&gt;name.' vocabulary');
	drupal_goto('admin/structure/taxonomy/'.$vocabulary-&gt;machine_name);
}

And that’s it!