views:

345

answers:

2

What is the function used to create taxonomy terms in Drupal from the code?

+4  A: 

Why don't check the API docs? The answer is right there. http://api.drupal.org/api/function/taxonomy_save_term/6

wimvds
Awesome. Now where to get an example of how to use it?
RD
+1 - This is the function to use, as it will invoke the appropriate hooks. NOTE: The function is a bit awkward to use, as it expects its parameter to be an array of the structure of a single term coming from the term edit page, which can vary a bit.
Henrik Opel
Scroll to the bottom of the page and read the comment, you'll find the example there.
wimvds
@RD: Ahem - have you scrolled down to the bottom of the linked API doc page? Simple example right there ;)
Henrik Opel
Yip. Just caught my eye now. Thanks.
RD
+1  A: 

A module I was writing needed a specific vocabulary with hierarchical terms. I wrote this function to save the terms:

<?php
/**
 * Save recursive array of terms for a vocabulary.
 *
 * Example:
 * <code><?php
 * $terms = array(
 *   'Species' => array(
 *     'Dog',
 *     'Cat',
 *     'Bird' ),
 *   'Sex' => array(
 *     'Male',
 *     'Female' ) )
 * _save_terms_recursive( $vid, $terms );
 * </code>
 *
 * @param int $vid Vocabulary id
 * @param array $terms Recursive array of terms
 * @param int $ptid Parent term id (generated by taxonomy_save_term) 
 */
function _save_terms_recursive( $vid, &$terms, $ptid=0 ) {
  foreach ( $terms as $k => $v ) {
    // simple check for numeric indices (term array without children)
    $name = is_string( $k ) ? $k : $v;
    $term = array( 'vid' => $vid, 'name' => $name, 'parent' => $ptid );
    taxonomy_save_term( $term );
    if ( is_array( $v ) && count( $v ) )
      _save_terms_recursive( $vid, $terms[ $k ], $term[ 'tid' ] );
  }
}
fresch