Created
January 21, 2017 11:38
-
-
Save himerus/f6875db8d3b6c575074c10fb4fb0df95 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(); | |
} |
Sorry for the inconvenience, you will have some manual how to install this module?
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 ;)
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
Thank you :)