Creating Drupal taxonomy terms from code?

半腔热情 提交于 2019-12-04 02:17:47

问题


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


回答1:


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




回答2:


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



回答3:


For Drupal 7, it's taxonomy_term_save(), by the way.




回答4:


Drupal 7 version looks like this:

/**
 * 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 );
        }
    }


来源:https://stackoverflow.com/questions/2424120/creating-drupal-taxonomy-terms-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!