从代码创建Drupal分类术语?

时间:2010-03-11 10:24:06

标签: php drupal taxonomy

从代码中用于在Drupal中创建分类术语的功能是什么?

4 个答案:

答案 0 :(得分:6)

为什么不检查API文档?答案就在那里。 http://api.drupal.org/api/function/taxonomy_save_term/6

答案 1 :(得分:2)

我写的一个模块需要一个带有分层术语的特定词汇表。我写了这个函数来保存术语:

<?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' ] );
  }
}

答案 2 :(得分:2)

对于Drupal 7,顺便说一下,它是taxonomy_term_save()

答案 3 :(得分:1)

Drupal 7版本看起来像这样:

/**
 * Save recursive array of terms for a vocabulary.
 *
 * Example of an array of terms:
 * $terms = array(
 *   'Species' => array(
 *     'Dog',
 *     'Cat',
 *     'Bird' ),
 *   'Sex' => array(
 *     'Male',
 *     'Female' ) );
 *
 * @param int $vid Vocabulary id
 * @param array $terms Recursive array of terms
 * @param int $ptid Parent term id (generated by taxonomy_save_term, when =0 then no parent)
 *
 * taxonomy_term_save ($term) gives back saved tid in $term
 * 
 **/
function _save_terms_recursively( $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 = new stdClass();
        $term->vid = $vid;
        $term->name = $name;
        $term->parent = $ptid;
        taxonomy_term_save( $term );

        if ( is_array( $v ) && count( $v ) ) {
            _save_terms_recursively( $vid, $terms[ $k ], $term->tid );
        }
    }