Creating Drupal taxonomy terms from code?

2019-02-20 16:33发布

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

4条回答
孤傲高冷的网名
2楼-- · 2019-02-20 17:00

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-20 17:07

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 );
        }
    }
查看更多
Rolldiameter
4楼-- · 2019-02-20 17:14

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' ] );
  }
}
查看更多
混吃等死
5楼-- · 2019-02-20 17:26

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

查看更多
登录 后发表回答