I'm using custom drush command for flushing my custom vocabulary:

    function drush_mm_category_delete_all() {
  $vocab = \Drupal\taxonomy\Entity\Vocabulary::load('mm_vocab');

  if (! $vocab) {
    throw new Exception("Missing 'mm_vocab' vocabulary");

  $tree = \Drupal::service('entity_type.manager')
    ->loadTree('mm_vocab', 0, NULL, FALSE);

  drush_print('Amount of terms to delete: ' . count($tree));
  $counter = 0;

  foreach($tree as $term) {
    $term_entity = \Drupal\taxonomy\Entity\Term::load($term->tid);

  drush_print('Amount of deleted terms: ' . $counter);


I'm getting error:

Error: Call to a member function delete() on null

but WTF? I see that loadTree returns flat array of all vocab term. It seems that all items are object with tid property.

If I add:

if ($term_entity) {
  //delete here

I'm able to run command without error, but only small amount of terms are deleted. Why?

  • Ok it's probably because upon parent deletion, children are also deleted.
    – Codium
    Aug 25, 2016 at 11:11

1 Answer 1


The comment is correct, children are deleted automatically.

So what you can do is set the max_depth argument to 0, then you should only get the top-level terms and you can delete those.

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.