Skip to content

Instantly share code, notes, and snippets.

@sprklinginfo
Forked from himerus/nodemaker_term_create.php
Created September 19, 2019 20:27
Show Gist options
  • Save sprklinginfo/4ded5898d962b69f2a9646862be038e6 to your computer and use it in GitHub Desktop.
Save sprklinginfo/4ded5898d962b69f2a9646862be038e6 to your computer and use it in GitHub Desktop.
Create a taxonomy term programmatically in Drupal 8.
<?php
/**
* @file
* Contains various helper functions.
*/
use Drupal\taxonomy\Entity\Term;
/**
* Helper function to create a taxonomy term programmatically.
*
* @code
* // Create top level term
* $term_id = _nodemaker_term_create('My Term', 'my_vocab', []);
*
* // Create term with parent term with an id of 999
* $term_id = _nodemaker_term_create('My Term', 'my_vocab', [999]);
* @endcode
*
* @param string $term
* - Term Name.
* @param string $vocabulary
* - System id of the vocabulary term will be added to.
* @param array $parent
* - Array of term ids to be assigned as parent.
*
* @return int|null
* - Returns the term id of the created term on success, null on failure.
*/
function _nodemaker_term_create($term, $vocabulary, array $parent = []) {
// Create the taxonomy term.
$new_term = Term::create([
'name' => $term,
'vid' => $vocabulary,
'parent' => $parent,
]);
// Save the taxonomy term.
$new_term->save();
// Return the taxonomy term id.
return $new_term->id();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment