Skip to content

Instantly share code, notes, and snippets.

@himerus
Created January 21, 2017 11:38
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save himerus/f6875db8d3b6c575074c10fb4fb0df95 to your computer and use it in GitHub Desktop.
Save himerus/f6875db8d3b6c575074c10fb4fb0df95 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();
}
@martin-klima
Copy link

Thank you :)

@Isidro-hernndez
Copy link

Sorry for the inconvenience, you will have some manual how to install this module?

@tarto-dev
Copy link

Sorry for that necroposting.

@Isidro-hernndez, this is a snippet.

You just have to add "use Drupal\taxonomy\Entity\Term;" in your file header, and L34->L44 code ;)

@DonRichards
Copy link

Thanks! Just gonna add this to my module!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment