-
-
Save shelane/856b53dec162c7a9418a4b0cc23acfa9 to your computer and use it in GitHub Desktop.
Create a taxonomy term programmatically in Drupal 8.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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