I want to remove all the terms from a vocab but not delete the vocab itself.

I can do it on the database, but Id rather use the api if available in D8.

$existingTerms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('mycustomvocab');
foreach ($existingTerms as $existingTerm) {
  // Delete vocabulary term *** This function is not available in D8 ***

  // Delete vocabulary - *** Not what is required ***
  $vocab = Vocabulary::load($existingTerm->vid);
  if (!is_null($vocab)) {

This is how Im doing it at the moment until I find a better solution

db_query("DELETE FROM {taxonomy_term_hierarchy} WHERE `tid` IN (SELECT tid FROM {taxonomy_term_data} WHERE `vid` = :ctype)", array(':ctype' => 'mycustomvocab'));  
db_query("DELETE FROM {taxonomy_term_field_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));
db_query("DELETE FROM {taxonomy_term_data} WHERE `vid` = :ctype", array(':ctype' => 'mycustomvocab'));

3 Answers 3

  $tids = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'mycustomvocab')

  $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  $entities = $controller->loadMultiple($tids);

Just noting another approach to delete the taxonomy term individually, useful for some cases:

// Example to load and delete a taxonomy term
$tid = 12;
if ($term = \Drupal\taxonomy\Entity\Term::load($tid)) {
  // Delete the term itself

*If you have access to Drupal Shell run following commands : drupal shell

*Then copy and paste following

function truncate_vocab($vid){
    $tids = \Drupal::entityQuery("taxonomy_term")->condition("vid",$vid)->execute();
    $controller = \Drupal::entityManager()->getStorage('taxonomy_term');
    $entites = $controller->loadMultiple($tids);
$vocabs = taxonomy_vocabulary_get_names();
foreach($vocabs as $vid){

I will try to make it a Drupal Shell command in future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.