taxonomy

Delete all terms

Submitted by root on Thu, 11/19/2020 - 07:28
Code
<?php $tids = \Drupal::entityQuery('taxonomy_term')->condition('vid', 'mycustomvocab')->execute(); $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term'); $entities = $controller->loadMultiple($tids); $controller->delete($entities); ?>

Save node terms

Submitted by root on Thu, 11/05/2020 - 17:08
Code
<?php $term_names = ['Bat', 'Bi']; $node_terms = []; foreach ($term_names as $name) { $tids = \Drupal::entityQuery('taxonomy_term')->condition('vid', 'vocabulary_id')->condition('name', $name)->execute(); if(!$tids) { $term = \Drupal\taxonomy\Entity\Term::create([ 'vid' => 'vocabulary_id', 'name' => $name, ]); $term->save(); $node_terms[] = ['target_id' => $term->id()]; } else { $node_terms[] = ['target_id' => array_shift($tids)]; } } $node->field_field_name->setValue($node_terms); ?>

Get translated taxonomy

Submitted by root on Thu, 11/05/2020 - 16:31
Code
<?php $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('vid', 0, NULL, TRUE); $current_langcode = \Drupal::languageManager()->getCurrentLanguage()->getId(); foreach ($terms as &$term) { if ($term->hasTranslation($current_langcode)) { $term = $term->getTranslation($current_langcode); } } ?>