Search code examples
drupaltaxonomydrupal-taxonomy

Save programmatically nested taxonomy term at once


the code below allows to create taxonomy terms using Drupal API

$terms = array(   

      $term1 = array(
      'name' => 'term name', 
      'description' => '', 
      'parent' => array(0), 
      'vid' => $vid,
       ),

      $term2 = array(
      'name' => 'term name', 
      'description' => '', 
      'parent' => array(0), 
      'vid' => $vid,
       ),

      $term3 = array(
      'name' => 'term name', 
      'description' => '', 
      'parent' => array(0), 
      'vid' => $vid,
       ),
);

foreach ($terms as $term) {
$term = (object) $term;
taxonomy_term_save($term);

}

It working well for sibling terms but what if I need to create nester taxonomy tree? There is 'parent' key that should contain array of parent term ids to do that

How will I know these IDs before parent terms get saved in DB?


Solution

  • The key is added to the passed term object by taxonomy_term_save (more specifically by taxonomy_term_save calling drupal_write_record):

    $term1 = array(
          'name' => 'term name', 
          'description' => '', 
          'parent' => array(0), 
          'vid' => $vid,
    );
    $term1 = (object) $term1;
    taxonomy_term_save($term1);
    echo $term1->tid; // now where did that come from?