Якщо визначена чітка ціль і присутня шалена мотивація, успішний результат гарантований. (с)

Програмне створення терміна таксономії Drupal на прикладах

Приклади для Drupal 7

/**
* Create a taxonomy term and return the tid.
*/
function custom_create_taxonomy_term($name, $vid, $parent_id = 0) {
  $term = new stdClass();
  $term->name = $name;
  $term->vid = $vid;
  $term->parent = array($parent_id);
  taxonomy_term_save($term);
  return $term->tid;
}

$term = new stdClass();
$vid = 3;
$term->name = 'testc' ;  
$term->description = 'This is test description';
$term->vid = $vid;
$term->parent = $parent_id;             
taxonomy_term_save($term);
drupal_set_message('term added');

// Create a new term programmatically.
  $newterm = new stdClass();
  $newterm->name = 'My term'; // The name of the term
  $newterm->vid = $vid; // The ID of the parent vocabulary
  $newterm->parent = 0; // This tells taxonomy that this is a top-level term
  taxonomy_term_save($newterm);

Інфо

 

Інфо 

Як створити простенький модуль для Drupal 8 - тут.

 

/**

* @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();

}

Джерело

Категорія