Skip to content

Instantly share code, notes, and snippets.

@cesarmiquel
Last active October 9, 2018 03:55
Show Gist options
  • Save cesarmiquel/de6c097da7e052354254f830c6300ae0 to your computer and use it in GitHub Desktop.
Save cesarmiquel/de6c097da7e052354254f830c6300ae0 to your computer and use it in GitHub Desktop.
Create Drupal 8 taxonomy terms off a YML file. Only two levels are supported.
<?php
use Symfony\Component\Yaml\Yaml;
use Drupal\taxonomy\Entity\Term;
$config = Yaml::parse(file_get_contents(DRUPAL_ROOT . '/sites/default/files/import.yml'));
$vocabulary = $config['vocabulary'];
foreach($config['terms'] as $term => $kids) {
$parent_term = Term::create([
'parent' => [],
'name' => $term,
'vid' => $vocabulary,
]);
$parent_term->save();
if (!is_array($kids)) {
$kids = [];
}
foreach($kids as $kid) {
Term::create([
'name' => $kid,
'parent' => $parent_term->ID(),
'vid' => $vocabulary,
])->save();
}
}
vocabulary: 'test_taxonomy'
terms:
'term 1':
- 'term 2'
- 'term 3'
'term 4':
- 'term 5'
- 'term 6'
'term 5':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment