11

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 ***
  taxonomy_term_delete($existingTerm->tid);

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

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

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

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

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
  $term->delete();
}
1

*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);
    $controller->delete($entites);
}
$vocabs = taxonomy_vocabulary_get_names();
foreach($vocabs as $vid){
   truncate_vocab($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.