Since Drupal 9 you can get this error:
Error: Call to undefined method Drupal\taxonomy\Entity\Term::getVocabularyId()
Here is the solution: (remove the line with - and change with + line)
- $vocabulary = Vocabulary::load($term->getVocabularyId());
+ $vocabulary = Vocabulary::load($term->bundle());