Create a Taxonomy Term Programmatically in Drupal
We know Taxonomy is a powerful core module and helps us categorize the content. A vocabulary in Drupal is essentially a container for terms that are used by the system. These terms are what Drupal uses to connect certain areas together within the website.
In Drupal, we can see the taxonomy module at Administer>Structure>Taxonomy. From here we can add the vocabulary and terms. We can also create taxonomy vocabularies and terms programmatically. Before you add a term, you need to make sure that the vocabulary is already there. Here is a way to create Taxonomy Vocabulary when you install the module for the first time.
Add the following code inside a function to create a term whenever you need it1 .
$new_term = Term::create([ 'vid' => 'vocabulary', 'name' => 'term name', ]); $new_term->enforceIsNew(); $new_term->save();
It is also possible to import taxonomy terms in bulk. Check out our Bulk Importing Taxonomy Terms in Drupal Using Custom Drush Command how-to.