Setting Up Drupal Taxonomy and Vocabularies
Drupal taxonomy is a content classification mechanism. Vocabularies are categories of classifiers (Genre, Tag, Region), Terms are specific values within vocabulary (Fiction, Moscow).
Creating a Vocabulary
Structure → Taxonomy → Add vocabulary. Name, description, machine name — used in code and URL.
Or via Drush:
drush php-eval "
\$vocab = \Drupal\taxonomy\Entity\Vocabulary::create([
'vid' => 'product_category',
'name' => 'Product Category',
]);
\$vocab->save();
"
Adding Taxonomy Field to Content Type
Structure → Content Types → [type] → Manage fields → Add field → Link to Taxonomy Term.
Field settings:
- Vocabulary: select created one
- Number of values: 1 (one category) or Unlimited (tags)
- Widget: Autocomplete (for tags) or Select list (for categories)
Hierarchical Taxonomy
Terms can have parents — builds tree. Example: Clothing → Men's Clothing → T-shirts.
use Drupal\taxonomy\Entity\Term;
// Create term with parent
$parent = Term::create([
'vid' => 'product_category',
'name' => 'Clothing',
]);
$parent->save();
$child = Term::create([
'vid' => 'product_category',
'name' => 'Men\'s Clothing',
'parent' => $parent->id(),
]);
$child->save();
Views for Category Pages
Views → Add view → content type, filter by taxonomy field. For automatic term pages — enable Views Taxonomy Term in view configuration.
// Programmatic query of nodes by taxonomy term
$query = \Drupal::entityQuery('node')
->condition('type', 'product')
->condition('field_category.entity.tid', $term_id)
->condition('status', 1)
->sort('created', 'DESC')
->accessCheck(TRUE)
->pager(20);
$nids = $query->execute();
$nodes = Node::loadMultiple($nids);
URL Aliases for Terms
Pathauto module automatically generates URLs: /catalog/[term:name]. Setup: Configuration → Search and metadata → URL aliases → Pathauto → templates for taxonomy.
Timelines
Creating vocabularies, adding fields to content types, setting up Views for category pages — 3–5 hours.







