2010-03-11 67 views

回答

6

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

+0

真棒。现在从哪里得到如何使用它的例子? – coderama

+2

+1 - 这是要使用的函数,因为它会调用适当的钩子。注意:该函数使用起来有点不方便,因为它期望它的参数是来自术语编辑页面的单个词语的结构数组,它可能会有所不同。 –

+0

滚动到页面底部并阅读评论,你会发现那里的例子。 – wimvds

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' ]); 
    } 
} 
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); 
     } 
    } 
相关问题